addClass()方法
addClass(className)
为所有匹配的元素添加类,添加多个类名时用空格分开。
.addClass( function(index, currentClass) )
index表示选择的元素在匹配元素集合中索引的位置
currentClass表示元素当前的class属性值
addClass()
通常与removeClass()
方法配合使用
$("p").removeClass("yourClass").addClass("myclass") //为所有的p元素移除yourClass添加一个myclass类
为集合中的索引为1的元素,或者原本class值为red的元素添加一个myclass类:
$("p").addClass(function(index,currentClass){
if(index==1||currentClass=="red"){
return "myclass";
}
})
removeClass()方法
removeClass(className)
为所有匹配的元素删除类,删除多个类名时用空格分开。不指定时,删除全部的类
.removeClass( function(index, class) )
index表示选择的元素在匹配元素集合中索引的位置
currentClass表示元素当前的class属性值
$("p").removeClass("myclass") //删除了myclass的类
attr()方法
.attr( attributeName )
attr()方法只获取集合中第一个元素对应属性。attrbuteName规定了属性名字(必须),如果需要获取所有元素的属性值,需要用each()或者map()方法循环
<div id="id1">Zero-th</div>
<div id="id2">First </div>
<div id="id3">Second </div>
<span></span> //id1 id2 id3
$(function(){
$("div").each(function(){
$("span").append($(this).attr("id")+" ");
})
})
若要检索和更改DOM属性,比如元素的checked, selected, 或 disabled状态,请使用.prop()方法。
if ( elem.checked ) //ture
if ( $(elem).prop("checked") ) //true
if ( $(elem).is(":checked") ) //true
$(elem).attr("checked") //"checked" 返回的不是Boolean值,而是字符串
设置属性时,设置的是全部匹配的元素
.attr( attributeName, value )
<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />
$('#greatphoto').attr('alt', 'Beijing Brush Seller'); //重写了img中的alt属性
.attr( attributes )
采用键值对的形式添加多个属性,注意:当属性值为class时,必须加引号,即“class”
$("#greatphoto").attr({
alt: 'Beijing Brush Seller',
title: 'photo by Kelly Clark'
})
.attr( attributeName, function(index, attr) )
index 为匹配集合中的索引
attr为原来的属性值。
$('#greatphoto').attr('title', function(i, val) {
return val + ' - photo by Kelly Clark'
});
removeAttr()方法
.removeAttr( attributeName )
为匹配集合中的所有元素删除一个或者多个属性,多个属性时用空格分开。
prop()方法
prop()方法类似于attr()方法,主要用来设置特性的值(boolean),如 checked
disabled
selectedIndex
, tagName
, nodeName
, nodeType
, ownerDocument
, defaultChecked
, 和 defaultSelected
同样的,获取时只能获取集合中第一个元素的值,设置时设置集合中所以元素的值
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" checked="checked" />
$("input[type='checkbox']").prop({
disabled: true //将所有的复选框都禁用。
});
removeProp()方法
用来移除通过prop()方法添加的特性。移除后获取该特性时取得的为undefined
注意:不要使用此方法来删除原生的属性( property ),比如checked, disabled, 或者 selected。这将完全移除该属性,一旦移除,不能再次被添加到元素上。使用.prop()来设置这些属性设置为false代替。
hasClass()方法
.hasClass()方法
用来判断元素集合中任何一个元素是否存在某个类。
<p>This paragraph is black and is the first paragraph.</p>
$("p").hasClass("foo"); //false
HTML()方法
.html()方法
获取元素集合中第一个元素的HTML内容。.html(stringhtml)
为元素集合中所有的元素添加一段html代码。.html(function(index,oldhtml))