jquery设置div,文本框 表单的值示例

我们将使用前一章中的三个相同的方法来设置内容:

text() - 设置或返回所选元素的文本内容

html() - 设置或返回所选元素的内容(包括 HTML标记)

val() - 设置或返回表单字段的值

1、html()方法

该方法类似于js当中的innerHTML属性

$("#two").html()方法 获取html

$("#two").html("<span>你好!</span>")

2、text()

类似于JS中的innerText属性

$("div").text() //获取div的文本内容

$("div").text("你好!"); //设置div的文本内容。

3、val()

类似于JS中的value属性

$("input[type=text]").val() //获取input的值

$("input[type=text]").val() //设置input的值。

vla()方法还有另外一个用处,就是它能使select 、checkbox、和radio 相应的选项被选中。

$(":radio").val("选择2号")设置ID号为single的单选框的选中值为“选择2号”

$(":checkbox").val("check2,check3") 设置多个选项.

下面的例子演示如何通过 text()、html() 以及 val() 方法来设置内容:

实例

代码如下 复制代码

$("#btn1").click(function(){

$("#test1").text("Hello world!");

});

$("#btn2").click(function(){

$("#test2").html("<b>Hello world!</b>");

});

$("#btn3").click(function(){

$("#test3").val("Dolly Duck");

});

text()、html() 以及 val() 的回调函数

上面的三个 jQuery 方法:text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。

下面的例子演示带有回调函数的 text() 和 html():

实例

代码如下 复制代码

$("#btn1").click(function(){

$("#test1").text(function(i,origText){

return "Old text: " + origText + " New text: Hello world!

(index: " + i + ")";

});

});

$("#btn2").click(function(){

$("#test2").html(function(i,origText){

return "Old html: " + origText + " New html: Hello <b>world!</b>

(index: " + i + ")";

});

});

更多详细内容请查看:http://www.111cn.net/wy/jquery/56679.htm