1.三个简单实用的用于 DOM 操作的 jQuery 方法:
- text() - 设置或返回所选元素的文本内容
- html() - 设置或返回所选元素的内容(包括 HTML 标记)
- val() - 设置或返回表单字段的值
eg:
通过 jQuery text() 和 html() 方法来获得内容:
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
通过 jQuery val() 方法获得输入字段的值:
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
下面的例子演示带有回调函数的 text() 和 html():
<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/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 <b>world!</b> (index: " + i + ")";
});
});
});
</script>
</head>
<body>
<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>
<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>
</body>
</html>
Attr():
jQuery attr() 方法用于获取属性值。
eg:
$("button").click(function(){
alert($("#w3s").attr("href"));
});
attr设置属性
jQuery attr() 方法也用于设置/改变属性值。
下面的例子演示如何改变(设置)链接中 href 属性的值:
$("button").click(function(){$("#w3s").attr("href","http://www.w3cschool.cc/jquery");
});
attr() 方法也允许您同时设置多个属性。
下面的例子演示如何同时设置 href 和 title 属性:
$("button").click(function(){$("#w3s").attr({
"href" : "http://www.w3cschool.cc/jquery",
"title" : "W3Schools jQuery Tutorial"
});
});
attr回调函数
jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
下面的例子演示带有回调函数的 attr() 方法:
$("button").click(function(){$("#w3s").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});