1、获取属性 - attr()
jQuery attr() 方法用于获取属性值。
语法:$(selector).attr(attribute)
attribute规定要获取其值的属性。
下面的例子演示如何获得链接中 href 属性的值:
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#w3s").attr("href"));
});
});
</script>
</head>
<body>
<p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
<button>显示 href 值</button>
</body>
</html>
2、设置属性 - attr()
jQuery attr() 方法也用于设置/改变属性值。
语法:$(selector).attr(attribute,value)
attribute规定属性的名称。
value规定属性的值。
下面的例子演示如何改变(设置)链接中 href 属性的值:
<!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.w3school.com.cn/jquery");
});
});
</script>
</head>
<body>
<p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
<button>改变 href 值</button>
<p>请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。</p>
</body>
</html>
attr() 方法也允许您同时设置多个属性。
语法:$(selector).attr({attribute:value, attribute:value ...})
attribute:value规定一个或多个属性/值对。
下面的例子演示如何同时设置 href 和 title 属性:
<!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.w3school.com.cn/jquery/",
"title" : "W3School 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>
3、attr() 的回调函数
jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
语法:$(selector).attr(attribute,function(index,oldvalue))
attribute规定属性的名称。
function(index,oldvalue) 规定返回属性值的函数。该函数可接收并使用选择器的 index 值和当前属性值。
下面的例子演示带有回调函数的 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", function(i,origValue){
return origValue + "/jquery";
});
});
});
</script>
</head>
<body>
<p><a href="http://www.w3school.com.cn" id="w3s">w3school.com.cn</a></p>
<button>改变 href 值</button>
<p>请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。</p>
</body>
</html>
4、removeAttr()从所有匹配的元素中移除指定的属性
removeAttr() 方法从被选元素中移除属性。
语法:$(selector).removeAttr(attribute)
attribute 必需。规定从指定元素中移除的属性。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").removeAttr("style");
});
});
</script>
</head>
<body>
<h1>这是一个标题</h1>
<p style="font-size:120%;color:red">这是一个段落。</p>
<p>这是另一个段落。</p>
<button>删除所有 p 元素的 style 属性</button>
</body>
</html>