返回值:Stringtext()

选择所有文本输入框,即 type 为 text 的元素。不包括 textarea 元素。

$(':text') 等价于 $('[type=text]')。如其他伪类选择器(以 ":" 开头的选择器)一样,建议使用此类选择器时,跟在一个标签名或者其他选择器后面;否则,默认使用了全局通配符选择器 "*" 。换句话说,$(':text') 等价于 $('*:text'),所以应该使用 $('input:text') 来提升匹配效率。

示例:

查找所有文本框。

<!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>
演示:

返回值:jQuerytext(textString)

Get the combined text contents of each element in the set of matched elements, including their descendants.

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

The .text() method cannot be used on input elements. For input field text, use the .val() 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; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>Test Paragraph.</p>

<script>

$("p").text("<b>Some</b> new text.");

</script>
</body>
</html>
演示: