jquery获取html元素内容的方法:1、使用html(),可返回被选元素的内容,语法“$(selector).html()”;2、使用text(),可返回被选元素的文本内容,语法“$(selector).text()”。
本教程操作环境:windows10系统、jquery1.8.3,本文适用于所有品牌的电脑。
【相关推荐:jquery视频教程】
1、html():返回原始html文档、但是在ie中可能存在兼容性,具体如下
原理:使用innerhtml()<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>document</title></head><body> <p id="box"> <p class="b2">我是一个p元素</p> <span>你好</span> </p></body><script src="libs/jquery-1.8.3.min.js"></script><script type="text/javascript"> $(function(){ var str = $("#box").html(); console.log(str); // <p>我是一个p元素</p> // <span>你好</span> //解释:该方法使用的是js中的innerhtml()有些浏览器返回的结果可能不是原始文档的 html 源代码。例如,如果属性值只包含字母数字字符,internet explorer有时丢弃包裹属性值的引号 });</script></html>
2、text():得到匹配元素集合中每个元素的合并文本,包括他们的后代
.text() 方法不能使用在 input 元素或scripts元素上,input 或 textarea 需要使用 .val() 方法获取或设置文本值得到scripts元素的值,使用.html()方法<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>document</title></head><body> <p id="box"> <p class="b2">我是一个p元素</p> <span>你好</span> </p></body><script src="libs/jquery-1.8.3.min.js"></script><script type="text/javascript"> $(function(){ var str = $("#box").text(); console.log(str); // 我是一个p元素 // 你好 });</script></html>
3、val()方法
元素的值是通过 value 属性设置的。该方法大多用于 input 元素。
更多编程相关知识,请访问:编程课程!!
以上就是jquery怎么获取html元素的内容?的详细内容。