jQuery - 設(shè)置內(nèi)容和屬性
設(shè)置內(nèi)容 - text()、html() 以及 val()
我們將使用前一章中的三個相同的方法來設(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ù)
上面的三個 jQuery 方法:text()、html() 以及 val(),同樣擁有回調(diào)函數(shù)。回調(diào)函數(shù)有兩個參數(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.15014759268.cn/jquery");
});
嘗試一下 ?
attr() 方法也允許您同時設(shè)置多個屬性。
下面的例子演示如何同時設(shè)置 href 和 title 屬性:
實(shí)例
$("button").click(function(){
$("#w3s").attr({
"href" : "http://www.15014759268.cn/jquery",
"title" : "jQuery 教程"
});
});
嘗試一下 ?
提示:請參考本站內(nèi)容獲取有關(guān) jQuery attr()方法的更多信息!
attr() 的回調(diào)函數(shù)
jQuery 方法 attr(),也提供回調(diào)函數(shù)。回調(diào)函數(shù)由兩個參數(shù):被選元素列表中當(dāng)前元素的下標(biāo),以及原始(舊的)值。然后以函數(shù)新值返回您希望使用的字符串。
下面的例子演示帶有回調(diào)函數(shù)的 attr() 方法:
實(shí)例
$("button").click(function(){
$("#w3cschool").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});
嘗試一下 ?
相關(guān)文章
對于 jQuery,具有操作 DOM 的能力很重要。jQuery 提供一系列與 DOM 相關(guān)的方法,這使訪問和操作元素和屬性變得很容易:詳細(xì)內(nèi)容請參考本站的“jQuery - DOM 操作”部分的內(nèi)容。
更多建議: