jQuery的属性操作, 是对html文档中的属性进行读取、设置和移除操作。比如,attr()、 removeAttr()。
1. attr()
attr()可以设置属性值或者返回被选元素的属性值
1.1 使用attr()获取值
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>attr()获取值</title>
<script type="text/javascript" src="jquery.js"></script>
<script> $(function () {
var cla = $("div").attr("class");
console.log(cla);
var id = $("div").attr("id");
console.log(id);
}) </script>
</head>
<body>
<div class="divClass" id="divId"></div>
</body>
</html>
结果为:
1.2 使用attr()设置值
1.2.1 使用attr()设置一个值
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>attr() Demo</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$("div").attr("class", "box");
})
</script>
</head>
<body>
<div></div>
<div></div>
</body>
</html>
结果显示为:
1.2.2 使用attr()设置多个值
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>attr() Demo</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$("div").attr({
"class": "divClass",
"id": "divId"
});
})
</script>
</head>
<body>
<div></div>
</body>
</html>
设置效果为:
2. removeAttr()
移除属性
2.1 删除单个属性
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>removeAttr() Demo</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$("div").removeAttr("class");
$("div").removeAttr("id");
})
</script>
</head>
<body>
<div class="divClass" id="divId"></div>
</body>
</html>
设置效果为:
2.2 removeAttr()设置多个属性值
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>removeAttr() Demo</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$("div").removeAttr("class id");
})
</script>
</head>
<body>
<div class="divClass" id="divId"></div>
</body>
</html>
显示结果为: