Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

jQuery attr()

jQuery attr()方法用于设置或返回所选元素的属性和值。
有两种用法jQuery attr()方法。
要返回属性值:此方法返回第一个匹配元素的值。 设置属性值:此方法用于设置一组匹配元素中的一个或多个属性/值对。
语法:
要返回属性值:
$(selector).attr(attribute)
设置属性和值:
$(selector).attr(attribute,value)
使用功能设置属性和值:
$(selector).attr(attribute,function(index,currentvalue))
设置多个属性和值:
$(selector).attr({attribute:value, attribute:value,...})

jQuery attr()方法的参数

参数 说明
attribute 此参数用于指定属性的名称。
value 此参数用于指定属性的值。
function(index,currentvalue) 是用于指定返回要设置的属性值的函数的参数。 index:它用于接收元素在集合中的索引位置。 currentvalue:用于提供所选元素的当前属性值。

jQuery attr()方法的示例

让我们以一个示例来演示jQuery attr()方法。
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("img").attr("width", "500");
    });
});
</script>
</head>
<body>
<img src="good-morning.jpg" alt="Good Morning Friends"width="284" height="213"><br>
<button>Set the width attribute of the image</button>
</body>
</html>
输出:
jquery attr设置图片

使用jQuery attr()方法的好处

它提供了两个主要好处:
便利性::当您使用jQuery attr()方法获取元素属性的值时,可以直接在jQuery对象上调用它并将其链接到其他jQuery方法。 跨浏览器一致性:您可以摆脱在不同浏览器甚至单个浏览器的不同版本上不一致更改属性值的麻烦。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4