原文链接:
在用Jquery修改HTML文件中某个部分的内容时,text()和html()是两个最常用的方法
例如下面的例子:
html()和text()设置值的时候:
html()相当于element.innerHTML()
text()是将字符串加入到元素中
html()和text()取值的时候:
<div><p>段落</p></div>
html()是取元素内容,包括标签也取出来,结果:<p>段落</p>
text()只取元素内容,不取标签,结果:段落
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.) Consider the following HTML:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> <ul> <li>list item 1</li> <li>list <strong>item</strong> 2</li> </ul> </div>
The code $('div.demo-container').text()
would produce the following result:
Demonstration Box list item 1 list item 2
Unlike the .html()
method, .text()
can be used in both XML and HTML documents.
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode()
, which replaces special characters with their HTML entity equivalents (such as <
for <
). Consider the following HTML:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> <ul> <li>list item 1</li> <li>list <strong>item</strong> 2</li> </ul> </div>
The code $('div.demo-container').text('<p>This is a test.</p>');
will produce the following DOM output:
<div class="demo-container"> <p>This is a test.</p> </div>
It will appear on a rendered page as though the tags were exposed, like this:
<p>This is a test</p>
This method is not available on XML documents.
In an HTML document, .html()
can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:
$('div.demo-container').html();
In order for the following <div>
's content to be retrieved, it would have to be the first one with class="demo-container"
in the document:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div>
The result would look like this:
<div class="demo-box">Demonstration Box</div>
The .html()
method is not available in XML documents.
When .html()
is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div>
The content of <div class="demo-container">
can be set like this:
$('div.demo-container') .html('<p>All new content. <em>You bet!</em></p>');
That line of code will replace everything inside <div class="demo-container">
:
<div class="demo-container"> <p>All new content. <em>You bet!</em></p> </div>