设置内容 - text()、html() 以及 val() 咱们将使用前一章中的三个相同的方法来设置内容: text() - 设置或返回所选元素的文本内容 html() - 设置或返回所选元素的内容(包括 HTML 标记) val() - 设置或返回表单字段的值 下面的例子演示如何经过 text()、html() 以及 val() 方法来设置内容: $("#btn1").click(function(){ $("#test1").text("Hello world!"); }); $("#btn2").click(function(){ $("#test2").html("Hello world!"); }); $("#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 world! (index: " + i + ")"; }); });
设置属性 - attr() jQuery attr() 方法也用于设置/改变属性值。 下面的例子演示如何改变(设置)连接中 href 属性的值: 实例 $("button").click(function(){ $("#w3s").attr("href",http://www.hello-code.com); }); attr() 方法也容许您同时设置多个属性。 下面的例子演示如何同时设置 href 和 title 属性: 实例 $("button").click(function(){ $("#w3s").attr({ "href" : http://www.hello-code.com, "title" : "编程中国社区" }); }); attr() 的回调函数 jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。而后以函数新值返回您但愿使用的字符串。 下面的例子演示带有回调函数的 attr() 方法: $("button").click(function(){ $("#w3s").attr("href", function(i,origValue){ return origValue + "/jquery"; }); }); 完整实例
<!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.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 world! (index: " + i + ")"; }); });
}); </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> <button id="btn1">显示旧/新文本</button> <button id="btn2">显示旧/新 HTML</button> </body> </html>php
转载于猿2048:☞《jquery给dom元素赋值的方法》html