例子 改变textarea的rows属性
1.
$(
"button"
).click(
function
(){
2.
$(
"textarea"
).attr(
"rows"
,
"30"
);
3.
});
第一种用于设置单个属性
attr( name , attribute)
参数:name字符串
参数:attribute字符串
返回值:jQuery对象
实例一 禁用所有索引数大于0的按钮
1.
$(
"button:gt(0)"
).attr(
"disabled"
,
"disabled"
);
attr( properties )
参数:properties 一个“键/值”形式的对象,属性名为“键”,属性值为“值”
返回值: jQuery对象
实例二
给img元素添加多项属性
1.
$(
"img"
).attr({
2.
src:
"/images/logo.gif"
,
3.
title:
"jquery"
,
4.
alt:
"jquery"
5.
});
6.
$(
"div"
).text($(
"img"
).attr(
"alt"
));
第三种 使用函数来设置属性/值
attr( key, fn )
参数: key String
参数: fn Function
返回值: jQuery 对象
解释:为所有匹配的元素设置一个计算的属性值。不提供值,而是提供一个函数,由这个函数计算的值作为属性值。fn参数可以带有一个参数,此参数为当前元素在jQuery集合中的索引数,fn中的this指代这个元素
实例三 针对div元素在页面中的位置来添加id属性值
1.
$(
"div"
).attr(
"id"
,
function
(arr) {
2.
return
"div-id"
+ arr;
3.
}).each(
function
() {
4.
$(
"span"
,
this
).html(
"(ID = '<b>"
+
this
.id +
"</b>')"
);
5.
});