上篇介紹 HTML Get,jQuery 其實使用上面同樣的三個方法來賦值。
比如下面代碼就是使用上面三種方法給 HTML 元素或 Form 賦值
$("#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()的回調(diào)函數(shù)
text(),html()和 val()方法可以和一個回調(diào)函數(shù)配合使用,這個回調(diào)函數(shù)具有兩個參數(shù),一個是選擇中元素的序號,第二個為當前值(舊值),然后你可以通過回調(diào)函數(shù)的返回值做為元素的新值。
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery Demo</title>
<script src="scripts/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$("#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 + ")";
});
});
});
</script>
</head>
<body>
<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>
<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>
</body>
</html>
http://wiki.jikexueyuan.com/project/jquery-tutorial/images/5.png" alt="" />
同樣為元素的屬性賦值也使用 attr()方法,例如:
$("button").click(function(){
$("#guidebee").attr({
"href" : "http://www.imobilebbs.com",
"title" : "imobilebbs jQuery Tutorial"
});
});