特性屬性:是指DOM元素中能夠和HTML元素中某個(gè)特性對(duì)應(yīng)得上的屬性。
下面就列出jQuery中提供的方法:
操作元素屬性:each(iterator)遍歷包裝集里所有元素,為各元素分別調(diào)用傳遞進(jìn)來的迭代器函數(shù)。參數(shù)iterator 一個(gè)函數(shù),為匹配集中的各元素分別調(diào)用一次。傳遞到函數(shù)的參數(shù)被設(shè)置為包裝集里當(dāng)前元素的下標(biāo)(從0開始),而當(dāng)前元素可通過函數(shù)this屬性來訪問。
$('img').each(function(n){
this.alt='This is image['+n+'] with an id of'+this.id;
})
獲取特性值:attr(name)獲取指派到包裝集里第一個(gè)元素指定特性的值。參數(shù) name為特性的名稱,該特性的值將被獲取。如果沒有該特性則返回undefined值。
<img id="myImage" src="image.gif" alt="An image" class="someClass" title="This is an image" custom="some value">
$("#myImage").attr("custom") 得到值就是some value。
設(shè)置特性值:attr(name,value)為包裝集里的所有元素的name特性設(shè)置傳遞進(jìn)來的值。name將被設(shè)置的特性的名稱,value指定特性的值。
$('*').attr('title',function(index) {
return 'I am element' '+ index +' and my name is ' +(this.id?this.id:'unset');
});
該函數(shù)是設(shè)置頁面上的所有元素的title特性為一個(gè)字符串。由DOM中元素的下標(biāo)和各個(gè)特定元素id特性值所組成的字符串。
attr()還可以一次設(shè)置多個(gè)特性到包裝集里所有元素的快速簡(jiǎn)便的方式。attr(attributes)。
$('input').attr(
{value:'',title:'please enter a value'}
);
該函數(shù)把所有<input>元素的value設(shè)置為空字符串,同時(shí)把title設(shè)置為字符串Please enter a value。