jQuery na nagtatakda at nagtatabi ng mga katangian
Itakda ang nilalaman - text(), html() at val()
Ginagamit namin ang tatlong parehong pamamaraan mula sa nakaraang kabanata upang itakda ang nilalaman:
- text() - Itakda o ibalik ang teksto ng napiling elemento
- html() - Itakda o ibalik ang nilalaman ng napiling elemento (kasama ang HTML na marka)
- val() - Itakda o ibalik ang halaga ng form na field
Ang mga halimbawa sa ibaba ay nagpapakita kung paano gamitin ang mga pamamaraan text(), html() at val() upang itakda ang nilalaman:
實例
$("#btn1").click(function(){ $("#test1").text("Hello world!"); }); $("#btn2").click(function(){ $("#test2").html("<b>Hello world!</b>"); }); $("#btn3").click(function(){ $("#test3").val("Dolly Duck"); });
Callback function ng text(), html() at val()
Ang tatlong jQuery na pamamaraan: text(), html() at val(), ay may callback function din. Ang callback function ay may dalawang argumento: ang pangalawang indeks ng kasalukuyang elemento sa napiling listahan, at ang orihinal (luma) na halaga. Pagkatapos, ibabalik ng function ang bagong halaga na gusto mong gamitin na string.
下面的例子演示帶有回調函數的 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 + ")"; }); });
設置屬性 - attr()
jQuery attr() 方法也用於設置/改變屬性值。
下面的例子演示如何改變(設置)鏈接中 href 屬性的值:
實例
$("button").click(function(){ $("#w3s").attr("href","http://www.codew3c.com/jquery"); });
attr() 方法也允許您同時設置多個屬性。
下面的例子演示如何同時設置 href 和 title 屬性:
實例
$("button").click(function(){ $("#w3s").attr({ "href" : "http://www.codew3c.com/jquery", "title" : "CodeW3C.com jQuery 教學" }); });
attr() 的回調函數
jQuery 方法 attr(),也提供回調函數。回調函數由兩個參數:被選元素列表中當前元素的下標,以及原始(舊的)值。然後以函數新值返回您希望使用的字串。
下面的例子演示帶有回調函數的 attr() 方法:
實例
$("button").click(function(){ $("#w3s").attr("href", function(i,origValue){ return origValue + "/jquery"; }); });