如何使用jQuery检索HTML标签的属性
在这篇文章中,我们将学习如何使用jQuery检索HTML标签的属性。我们可以使用JQuery在几行代码中完成这个任务。在这里,我们将建立一个图像缩放系统,看看如何能够检索和改变HTML标签的属性。
使用attr()方法:这个方法既可以用来设置属性,也可以用来返回属性,这完全取决于这个函数中传递的参数。
语法:
// Retrieve the value of the attribute
// of the first matched element
(selector).attr(attribute)
// Set the value of matched element's attribute(selector).attr(attribute, value)
// Set multiple attributes and values
$(selector).attr({attribute1: value1, attribute2: value2,...})
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
</head>
<body>
<h1></h1>
<img src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png"
alt="This is GFG Post"
width="250" height="250"><br>
<button>Zoom</button>
</body>
<script>
(document).ready(function () {
("button").click(function () {
// Setting width and image attribute
("img").attr(
{ "width": 500, "height": 500 }
);
// Retrieving alt attribute value from the image tag
const heading =("img").attr("alt");
$("h1").text(heading);
});
});
</script>
</html>
输出:
正如你在输出中看到的,点击缩放按钮后,图像标签的宽度和高度属性被改变。另外,我们从图像标签中获取了alt属性值,并将其设置在h1标签中。
上述任务也可以通过用prop方法替换attr()方法来完成,这不会对输出造成任何改变。现在问题来了,该用哪一个呢?
attr()和prop()的区别:attr()方法改变该HTML标签的属性,而prop()根据DOM树改变HTML标签的属性。让我们通过一个例子来理解这一点。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
</head>
<body>
<input type="text" name="test"
id="test" value="Test">
<button>Test</button>
</body>
<script>
(document).ready(function () {
("button").click(function () {
console.log(
"When using attr() method: " +
("#test").attr("value")
);
console.log(
"When using prop() method: " +
("#test").prop("value")
);
})
})
</script>
</html>
输出:
上面的输出显示,如果你想要任何HTML标签的默认值,那么,使用attr()函数。如果你想让属性值被用户改变(如输入、复选框、收音机等),那么使用prop()函数来获取更新的值。