jQuery - 設(shè)置內(nèi)容和屬性
設(shè)置內(nèi)容 - text()、html() 以及 val()
我們將使用前一章中的三個(gè)相同的方法來設(shè)置內(nèi)容:
下面的例子演示如何通過 text()、html() 以及 val() 方法來設(shè)置內(nèi)容:
實(shí)例
$("#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ù)
上面的三個(gè) jQuery 方法:text()、html() 以及 val(),同樣擁有回調(diào)函數(shù)。回調(diào)函數(shù)由兩個(gè)參數(shù):被選元素列表中當(dāng)前元素的下標(biāo),以及原始(舊的)值。然后以函數(shù)新值返回您希望使用的字符串。
下面的例子演示帶有回調(diào)函數(shù)的 text() 和 html():
實(shí)例
$("#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 + ")";
});
});
嘗試一下 ?
設(shè)置屬性 - attr()
jQuery attr() 方法也用于設(shè)置/改變屬性值。
下面的例子演示如何改變(設(shè)置)鏈接中 href 屬性的值:
實(shí)例
$("button").click(function(){
$("#w3s").attr("href","http://www.jyygyx.com/s/jquery");
});
嘗試一下 ? attr() 方法也允許您同時(shí)設(shè)置多個(gè)屬性。
下面的例子演示如何同時(shí)設(shè)置 href 和 title 屬性:
實(shí)例
$("button").click(function(){
$("#w3s").attr({
"href" : "http://www.jyygyx.com/s/jquery",
"title" : "jQuery 教程"
});
});
嘗試一下 ?
attr() 的回調(diào)函數(shù)
jQuery 方法 attr(),也提供回調(diào)函數(shù)。回調(diào)函數(shù)由兩個(gè)參數(shù):被選元素列表中當(dāng)前元素的下標(biāo),以及原始(舊的)值。然后以函數(shù)新值返回您希望使用的字符串。
下面的例子演示帶有回調(diào)函數(shù)的 attr() 方法:
實(shí)例
$("button").click(function(){
$("#w3s").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});
嘗試一下 ?