text()
得到匹配元素集合中每个元素的文本内容结合,包括他们的后代,或设置匹配元素集合中每个元素的文本内容为指定的文本内容。
.text ()
.text (textString)
- text(textString)
- text(function(index, text))
text()
得到匹配元素集合中每个元素的合并文本,包括他们的后代
.text()这个方法不接受任何参数。.text()和.html()方法不同,.text()在XML 和 HTML 文档中都能使用。.text()方法返回一个字符串,包含所有匹配元素的合并文本。(由于在不同的浏览器中的HTML解析器的变化,返回的文本中换行和其他空白可能会有所不同。)
考虑下面的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>
<script>$('div.demo-container').text();</script>
//将的得到下面的文本内容:
Demonstration Box list item 1 list item 2
.text()方法不能使用在 input 元素或scripts元素上。input或textarea需要使用.val()方法获取或设置文本值。得到scripts元素的值,使用.html()方法
从 jQuery 1.4开始,.text()方法返回文本内容和作为元素节点的CDATA 节点。
例子
找到第一段中的文本(去掉html),然后设置最后一段的html以显示它只是文本(红色粗体消失)。
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; margin:8px; }
b { color:red; }
</style>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.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>
text(textString)
设置匹配元素集合中每个元素的文本内容为指定的文本内容。
- .text(textString)类型: String。用于设置匹配元素内容的文本
- .text(function(index, text))类型:Function()。用来返回设置文本内容的一个函数。接收元素的索引位置和文本值作为参数。
.text()和.html()方法不同,.text()在XML 和 HTML 文档中都能使用。
我们必须意识到这种方法提供了必要的字符串从提供的正确的HTML中脱离出来。这样做,他调用DOM 方法.createTextNode(),一种替代的特殊字符与HTML对应(比如<替换为<)方法。考虑下面的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>
$('div.demo-container').text('<p>This is a test.</p>');代码语句将输出以下 DOM :
<div class="demo-container"> <p>This is a test.</p> </div>
它会出现在渲染的页面上就好像标签被暴露,像这样:
<p>This is a test</p>
.text()方法不能使用在 input 元素上。输入的文本需要使用.val()方法。
从 jQuery 1.4开始,.text()方法允许我们通过函数来传递文本内容。
$('ul li').text(function (index) {
return 'item number ' + (index + 1);
});
给定一个拥有3个<li>元素,在这个例子中将输出下面的DOM:
<ul> <li>item number 1</li> <li>item number 2</li> <li>item number 3</li> </ul>
例子
在段落中添加文本。注意这个<b>标签将从HTML中脱离出来。
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; margin:8px; }
</style>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
</head>
<body>
<p>Test Paragraph.</p>
<script>$("p").text("<b>Some</b> new text.");</script>
</body>
</html>
