1. 操作屬性
上文介紹了如何篩選到需要的元素。得到了元素之后就要對其進行操作。一個常見的需求是遍歷得到的元素集,對每一個元素進行一個操作。jQuery提供的函數(shù)是
each(iterator),其中iterator是一個函數(shù),接受一個整數(shù)作為參數(shù),表示第幾個元素。看一個簡單的例子。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Operation</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(function() {
$('img').each(function(n) {
this.alt = "This is " + n + "th picture";
});
});
</script>
</head>
<body>
<h1>Image Gallery<br />March 13th,2010</h1>
<img src="img/bee.jpg" alt="" width="150px"/>
<img src="img/bright.jpg" alt="" width="150px"/>
<img src="img/crowd.jpg" alt="" width="150px"/>
<img src="img/pink.jpg" alt="" width="150px"/>
<img src="img/white.jpg" alt="" width="150px"/>
</body>
</html>結(jié)果用Firebug查看下:
在上例中,采用了原生javascript的方法存取屬性,jQuery 提供了一個更加一般的方法來存取屬性,attr:
attr(name),如果name是字符串,獲得第一個元素的屬性的name的值;如果name是一個對象,則對象的屬性被作為元素的屬性而復(fù)制到包裝集的所有元素上。
attr(name,value),當name是字符串的時候,就把屬性name的值設(shè)置為value,當value是一個函數(shù)的時候,則對包裝集中的每個元素調(diào)用此函數(shù),將其name的值設(shè)置為函數(shù)的返回值。
看一個簡單的例子,html代碼仍然使用上面的:
<scripttype="text/javascript">
$(function() {
$('body').children().attr('title', function(n) {
return"This is "+ n + "th element";
});
$('img').attr('alt', 'A photo taken by YinZixin');
alert($('h1').attr('title'));
});
</script>
結(jié)果為:
要刪除屬性,使用removeAttr(name)方法。