返回值:Stringtext()
Get the combined text contents of each element in the set of matched elements, including their descendants.
-
1.0 新增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
.text()
method cannot be used on form inputs or scripts. To set or get the text value of input
or textarea
elements, use the
.val()
method. To get the value of a script element, use the
.html()
method.
As of jQuery 1.4, the .text()
method returns the value of text and CDATA nodes as well as element nodes.
示例:
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; margin:8px; }
b { color:red; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<p><b>Test</b> Paragraph.</p>
<p></p>
<script>
var str = $("p:first").text();
$("p:last").html(str);
</script>
</body>
</html>