清華大佬耗費三個月吐血整理的幾百G的資源,免費分享!....>>>
jQuery - 設置內容和屬性
設置內容 - text()、html() 以及 val()
我們將使用前一章中的三個相同的方法來設置內容:
- text() - 設置或返回所選元素的文本內容
- html() - 設置或返回所選元素的內容(包括 HTML 標記)
- val() - 設置或返回表單字段的值
下面的例子演示如何通過 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");
});
? $("#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 + ")";
? });
});
? $("#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 + ")";
? });
});
設置屬性 - attr()
jQuery attr() 方法也用于設置/改變屬性值。
下面的例子演示如何改變(設置)鏈接中 href 屬性的值:
實例
$("button").click(function(){
? $("#w3s").attr("href","http://www.w3cschool.cc/jquery");
});
? $("#w3s").attr("href","http://www.w3cschool.cc/jquery");
});
attr() 方法也允許您同時設置多個屬性。
下面的例子演示如何同時設置 href 和 title 屬性:
實例
$("button").click(function(){
? $("#w3s").attr({
??? "href" : "http://www.w3cschool.cc/jquery",
??? "title" : "W3Schools jQuery Tutorial"
? });
});
? $("#w3s").attr({
??? "href" : "http://www.w3cschool.cc/jquery",
??? "title" : "W3Schools jQuery Tutorial"
? });
});
attr() 的回調函數
jQuery 方法 attr(),也提供回調函數。回調函數由兩個參數:被選元素列表中當前元素的下標,以及原始(舊的)值。然后以函數新值返回您希望使用的字符串。
下面的例子演示帶有回調函數的 attr() 方法:
實例
$("button").click(function(){
? $("#w3s").attr("href", function(i,origValue){
??? return origValue + "/jquery";
? });
});
? $("#w3s").attr("href", function(i,origValue){
??? return origValue + "/jquery";
? });
});
掃碼二維碼 獲取免費視頻學習資料