- attr(): Get attribute value or set attribute
- When a parameter is passed to the method, the specified attribute is obtained for an element
- When passing two parameters for the method, set the specified attribute value for an element
- There are many methods in Jquery that are a function to get or set a value. For example: attr(),html(),text(),val(),height(),width(),css(), etc.
- removeAttr(): Remove the attribute of the specified element.
Example 1: Use attr() to get the value of the specified attribute of the specified element.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>attr()方法获取属性值</title>
<script src="jquery-1.11.3.js"></script>
</head>
<body>
<div title="你喜欢的运动" id="content">足球</div>
<script>
$(function(){
var $div=$("#content");
/*获取指定元素的指定属性的值*/
var title= $div.attr("title");
alert(title);
});
</script>
</body>
</html>
Example 2: Use attr() to set the value of the specified attribute of the specified element.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>使用attr()给指定的元素设置属性</title>
<script src="jquery-1.11.3.js"></script>
</head>
<body>
<ul id="fruit">
<li title="pg">苹果</li>
<li title="zj">橘子</li>
<li>香蕉</li>
</ul>
<script>
$(function(){
/*使用attr()给指定的元素设置属性*/
$("li:eq(2)").attr("title","xj").attr("style","color:red;font-size:20px;");
});
</script>
</body>
</html>
Example 3: Use removeAttr() to remove an attribute
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>使用removeAttr()移除某个元素属性</title>
<script src="jquery-1.11.3.js"></script>
</head>
<body>
<ul id="fruit">
<li title="pg">苹果</li>
<li title="zj">橘子</li>
<li>香蕉</li>
</ul>
<script>
$(function(){
/*"li[title='zj']":属性选择器
* 移除指定的属性
* */
$("li[title='zj']").removeAttr("title");
});
</script>
</body>
</html>
Originality is not easy, remember to give a thumbs up