13--DOM operation in Jquery (attribute node acquisition and setting)

  1. attr(): Get attribute value or set attribute
    1. When a parameter is passed to the method, the specified attribute is obtained for an element
    2. When passing two parameters for the method, set the specified attribute value for an element
  2. 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.
  3. 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

Guess you like

Origin blog.csdn.net/qwy715229258163/article/details/113876646