热门关键字:
jquery > jquery教程 > jquery教程 > jquery 设置属性方法attr()

jquery 设置属性方法attr()

410
作者:管理员
发布时间:2021/1/16 17:15:04
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=3180
例子 改变textarea的rows属性


$("button").click(function(){
  $("textarea").attr("rows","30");
});
第一种用于设置单个属性
attr( name , attribute) 
参数:name字符串 
参数:attribute字符串 
返回值:jquery对象
实例一 禁用所有索引数大于0的按钮


$("button:gt(0)").attr("disabled","disabled"); 
第二种 用于一次设置多个属性
attr( properties ) 
参数:properties 一个“键/值”形式的对象,属性名为“键”,属性值为“值”
返回值: jQuery对象


实例二


给img元素添加多项属性


$("img").attr({ 
        src: "/images/logo.gif", 
        title: "jquery", 
        alt: "jquery" 
}); 
$("div").text($("img").attr("alt")); 
第三种 使用函数来设置属性/值
attr( key, fn ) 
参数: key String 
参数: fn Function 
返回值:  jQuery 对象
解释:为所有匹配的元素设置一个计算的属性值。不提供值,而是提供一个函数,由这个函数计算的值作为属性值。fn参数可以带有一个参数,此参数为当前元素在jQuery集合中的索引数,fn中的this指代这个元素 


实例三 针对div元素在页面中的位置来添加id属性值


$("div").attr("id", function (arr) { 
        return "div-id" + arr; 
}).each(function () { 
        $("span", this).html("(ID = '<b>" + this.id + "</b>')"); 
}); 




如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:jQuery
友荐云推荐