概述 .text()
返回值:String
描述:得到匹配元素集合中每个元素的合并文本,包括他们的后代
和 .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>
代码$('div.demo-container').text()
将提供下面的结果:
Demonstration Box list item 1 list item 2
.text()
方法不能使用在 input 元素或scripts元素上。 input
或 textarea
需要使用 .val() 方法获取或设置文本值。得到scripts元素的值,使用.html()
方法
从 jQuery 1.4开始, .text()
方法返回文本内容和作为元素节点的CDATA 节点。
示例
返回p元素的文本内容。
$('p').text();
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 lang="en">
- <head>
- <meta charset="utf-8">
- <title>text demo</title>
- <style>
- p {
- color: blue;
- margin: 8px;
- }
- b {
- color: red;
- }
- </style>
- <script src="https://code.jquery.com/jquery-1.10.2.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 )
返回值:jQuery
描述:设置匹配元素集合中每个元素的文本内容为指定的文本内容。
String
or Number
or Boolean
和 .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>
示例
设置所有 p 元素的文本内容
$("p").text("Hello world!");
使用函数来设置所有匹配元素的文本内容。
$("p").text(function(n){
return "这个 p 元素的 index 是:" + n;
});
在段落中添加文本。注意这个<b>标签将从HTML中脱离出来。
运行一下
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>text demo</title>
- <style>
- p {
- color: blue;
- margin: 8px;
- }
- </style>
- <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
- </head>
- <body>
- <p>Test Paragraph.</p>
- <script>
- $( "p" ).text( "<b>Some</b> new text." );
- </script>
- </body>
- </html>