jQuery - 设置内容和属性
设置内容 - text(), html(), 和 val()
我们将使用上一页的三个方法来设置内容
text()
- 设置或返回选定元素的文本内容html()
- 设置或返回选定元素的内容(包括 HTML 标记)val()
- 设置或返回表单字段的值
以下示例演示了如何使用 jQuery 的 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");
});
自己动手试一试 »
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 + ")";
});
});
自己动手试一试 »
设置属性 - attr()
jQuery 的 attr()
方法也用于设置/更改属性值。
以下示例演示了如何更改(设置)链接中 href 属性的值
示例
$("button").click(function(){
$("#w3s").attr("href", "https://w3schools.org.cn/jquery/");
});
自己动手试一试 »
attr()
方法还允许您同时设置多个属性。
以下示例演示了如何同时设置 href 和 title 属性
示例
$("button").click(function(){
$("#w3s").attr({
"href" : "https://w3schools.org.cn/jquery/",
"title" : "W3Schools jQuery 教程"
});
});
自己动手试一试 »
attr() 的回调函数
jQuery 方法 attr()
也带有一个回调函数。回调函数有两个参数:选定元素列表中当前元素的索引和原始(旧)属性值。然后,您可以从函数中返回您想用作新属性值的字符串。
以下示例使用回调函数演示了 attr()
示例
$("button").click(function(){
$("#w3s").attr("href", function(i, origValue){
return origValue + "/jquery/";
});
});
自己动手试一试 »
jQuery 练习
jQuery HTML 参考
要查看所有 jQuery HTML 方法的完整概述,请访问我们的 jQuery HTML/CSS 参考。