jquery中val() (文章转载)


val在jquery中有两种用法,一种是直接获得第一个匹配元素的当前值。第二种是他也可以和attr一样设置每一个匹配元素的值。
一种:来自jquery文档
获得第一个匹配元素的当前值。
在 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 代码:
$("input").val();
结果:
some text
第二种:来自jquery文档
设置每一个匹配元素的值。
在 jQuery 1.2, 这也可以为select元件赋值

 

Set the value attribute of every matched element.
In jQuery 1.2, this is also able to set the value of select elements, but selecting the appropriate options.
返回值
jQuery
参数
val (String) : 要设置的值。
示例
设定文本框的值
HTML 代码:
<input type="text"/>
jQuery 代码:
$("input").val("hello world!");
jquery确实很好用,也很易用!也难怪这多人喜欢上他!
本文来源于php教程 http://www.phplover.cn/ , 原文地址:http://www.phplover.cn/post/jquery-val.html


 

posted @ 2012-02-19 10:06  一枚快乐滴海绵  阅读(330)  评论(0编辑  收藏  举报