首页 > 语言 > JavaScript > 正文

jquery 学习之二 属性 文本与值(text,val)

2024-05-06 14:26:30
字体:
来源:转载
供稿:网友

text()

取得所有匹配元素的内容。结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。Get the text contents of all matched elements.The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents.

返回值

String

示例

HTML 代码:

<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>

jQuery 代码:

$("p").text();

结果:

Test Paragraph.Paraparagraph ------------------------------------------------------------------------------------------------------------------------------

text(val)

设置所有匹配元素的文本内容与 html() 类似, 但将编码 HTML (将 "<" 和 ">" 替换成相应的HTML实体).Set the text contents of all matched elements.Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).

返回值

jQuery

参数

val (String) : 用于设置元素内容的文本

示例

HTML 代码:

<p>Test Paragraph.</p>

jQuery 代码:

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

结果:

[ <p><b>Some</b> new text.</p> ] ------------------------------------------------------------------------------------------------------------------------------

val()

获得第一个匹配元素的当前值。在 jQuery 1.2 中,可以返回任意元素的值了。包括select。如果多选,将返回一个数组,其包含所选的值。Get the content of the value attribute of the first matched element.In jQuery 1.2, a value is now returned for all elements, including selects. For multiple selects an array of values is returned. 

返回值

String,Array

示例

获得单个select的值和多选select的值。

HTML 代码:

<p></p><br/>
<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>
<select id="multiple" multiple="multiple">
  <option selected="selected">Multiple</option>
  <option>Multiple2</option>
  <option selected="selected">Multiple3</option>
</select>

jQuery 代码:

$("p").append(
  "<b>Single:</b> "   + $("#single").val() +
  " <b>Multiple:</b> " + $("#multiple").val().join(", ")
);

结果:

[ <p><b>Single:</b>Single<b>Multiple:</b>Multiple, Multiple3</p>]

获取文本框中的值

HTML 代码:

<input type="text" value="some text"/>

jQuery 代码:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选