设置内容 - text()、html() 以及 val()
我们将使用前一章中的三个相同的方法来设置内容:
text() - 设置或返回所选元素的文本内容 html() - 设置或返回所选元素的内容(包括 HTML 标记) val() - 设置或返回表单字段的值如何通过 text()、html() 以及 val() 方法来设置内容:
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("#test1").text("Hello world!"); }); $("#btn2").click(function(){ $("#test2").html("<b>Hello world!</b>"); }); $("#btn3").click(function(){ $("#test3").val("Dolly Duck"); }); }); </script> </head> <body> <p id="test1">这是段落。</p> <p id="test2">这是另一个段落。</p> <p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p> <button id="btn1">设置文本</button> <button id="btn2">设置 HTML</button> <button id="btn3">设置值</button> </body> </html>text()、html() 以及 val() 的回调函数
上面的三个 jQuery 方法:text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
带有回调函数的 text() 和 html():
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"></script> <script> $(document).ready(function(){ $("#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 + ")"; }); }); }); </script> </head> <body> <p id="test1">这是<b>粗体</b>文本。</p> <p id="test2">这是另一段<b>粗体</b>文本。</p> <button id="btn1">显示旧/新文本</button> <button id="btn2">显示旧/新 HTML</button> </body> </html>设置属性 - attr()
jQuery attr() 方法也用于设置/改变属性值。
attr() 方法允许您同时设置多个属性。
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#w3s").attr({ "href" : "http://www.baidu.com/jquery/", "title" : " jQuery 教程" }); }); }); </script> </head> <body> <p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p> <button>改变 href 和 title 值</button> <p>把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值和已经设置的 title 值。</p> </body> </html>attr() 的回调函数
jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
带有回调函数的 attr() 方法:
<!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("he").attr("href", function(i,origValue){ return origValue + "/jquery"; }); }); }); </script> </head> <body> <p><a href="http://www.baidu.com" id="he">baidu</a></p> <button>改变 href 值</button> <p>请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。</p> </body> </html>