jQuery学习3:操作元素属性和特性


  本文标签:jQuery,元素属性,特性

下面就列出jQuery中提供的方法:

操作元素属性:each(iterator)遍历包装集里所有元素,为各元素分别调用传递进来的迭代器函数 。参数iterator 一个函数,为匹配集中的各元素分别调用一次 。传递到函数的参数被设置为包装集里当前元素的下标(从0开始),而当前元素可通过函数this属性来访问 。

$(img).each(function(n){

this.alt=This is image[+n+] with an id of+this.id;

})

获取特性值:attr(name)获取指派到包装集里第一个元素指定特性的值 。参数 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 。

设置特性值:attr(name,value)为包装集里的所有元素的name特性设置传递进来的值 。name将被设置的特性的名称,value指定特性的值 。

$(*).attr(title,function(index) {

  return I am element + index + and my name is +(this.id?this.id:unset);

});

该函数是设置页面上的所有元素的title特性为一个字符串 。由DOM中元素的下标和各个特定元素id特性值所组成的字符串 。

attr()还可以一次设置多个特性到包装集里所有元素的快速简便的方式 。attr(attributes) 。

$(input).attr(

{value:,title:please enter a value}

);

该函数把所有<input>元素的value设置为空字符串,同时把title设置为字符串Please enter a value 。