本文摘自PHP中文网,作者醉折花枝作酒筹,侵删。
在javascript中,“html()”方法的用法是“元素.html(被选元素的新内容)”。html方法设置或返回被选元素的内容,当该方法用于返回内容时,则返回第一个匹配元素的内容;当该方法用于设置内容时,则重写所有匹配元素的内容。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
HTML内容就是内容中可以包含HTML标签,并且能够被浏览器渲染。
文本内容是先将内容中的HTML预定义字符转换成html字符实体,这样HTML标签就不会被渲染。
语法结构一:
此时方法不带参数时候是取得第一个匹配元素的html内容。
此方法与text()方法没有参数用法类似,但是还是有很大区别:
一.html()方法取得第一个匹配元素的内容,而text()方法是取得所有匹配元素包含的内容。
二.html()方法取得内容html内容,而text()方法取得是文本内容。
实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <!DOCTYPE html>
< html >
< head >
< meta charset = " utf-8" />
< meta name = "author" content = "https://www.jb51.net/" />
< title ></ title >
< style type = "text/css" >
div{
height:150px;
width:150px;
background-color:green;
margin-top:10px;
}
</ style >
< script type = "text/javascript" src = "mytest/jQuery/jquery-1.8.3.js" ></ script >
< script type = "text/javascript" >
$(document).ready(function () {
$("button").click(function () {
alert($("div").html());
});
});
</ script >
</ head >
< body >
< div >
< ul >
< li >
< span >欢迎您</ span >
</ li >
</ ul >
</ div >
< button >点击查看效果</ button >
</ body >
</ html >
|
以上代码将返回div元素中的内容。
语法结构二:
1 | $(selector).html(content)
|
带有参数的时候是设置所有匹配元素而的html内容。
此方法与text()方法带有参数的用法类似,但是还是有很大的区别:
html()方法设置的是html内容,而text()方法设置的是文本内容。
实例代码:
以下代码将div中的html内容设置为"<b>我是重新设置后的内容</b>"。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <!DOCTYPE html>
< html >
< head >
< meta charset = " utf-8" />
< meta name = "author" content = "https://www.jb51.net/" />
< title >脚本之家</ title >
< style type = "text/css" >
div
{
height:150px;
width:150px;
background-color:green;
margin-top:10px;
}
</ style >
< script type = "text/javascript" src = "mytest/jQuery/jquery-1.8.3.js" ></ script >
< script type = "text/javascript" >
$(document).ready(function () {
$("button").click(function () {
$("div").html("< b >我是重新设置后的内容</ b >");
});
});
</ script >
</ head >
< body >
< div >原来内容</ div >
< button >点击查看效果</ button >
</ body >
</ html >
|
【推荐学习:javascript高级教程】
以上就是jquery中html()方法怎么用的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
jQuery怎么绑定click事件
jQuery不兼容ie浏览器怎么办
jQuery如何判断鼠标是否在某个元素内
jQuery与javascript有什么关系?
jQuery不兼容低版本ie浏览器怎么办
详解jQuery中的get方法
jQuery判断函数是否存在的方法
jQuery选择器优点有什么
jQuery的$().each和$.each的区别是什么?
jQuery可见性过滤选择器有哪些
更多相关阅读请进入《jQuery》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » jquery中html()方法怎么用