getAttribute() 與 attr() 的區別

一直覺得 getAttribute() 和 attr() 都是獲取元素屬性的方法,只是一種是 JS 寫法,一種是 JQ 寫法,但其實它們是有區別的。javascript

主要區別

調用 getAttribute() 的主體必須是元素(Object Element)
調用 attr() 的主體必須是對象(Object Object)html

JS寫法:getAttribute()

getAttribute() 是元素(Element)下的一種方法,所以想調用這個方法,必須確保它的調用主體是元素,不然會報錯。java

正確使用方式:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="test" custom="hello"></div>
        <script type="text/javascript">
            var div = document.getElementById('test');
            //獲取的div是[object HTMLDivElement]
            alert(div.getAttribute('custom'));
        </script>
    </body>
</html>
錯誤使用方式:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="test" custom="hello"></div>
        <script type="text/javascript">
            var div = $('#test');
            //獲取的div是[object Object]
            alert(div.getAttribute('custom'));
        </script>
    </body>
</html>

經過 JQ 選擇器獲取 div,此時的 div 是對象(Object)也就沒法調用 getAttribute() 方法,瀏覽器(Safari)會報錯以下:jquery

TypeError: div.getAttribute is not a function. (In 'div.getAttribute('custom')', 'div.getAttribute' is undefined)

JQ寫法:attr()

Get the value of an attribute for the first element in the set of matched elements.

jQuery API Documentation 中對 attr() 方法——準確說是 attr( attributeName ) 方法的描述是「獲取一組相匹配元素中首個元素的屬性值」。
描述中的「一組元素」應該指的是對象(Object),而不是多個元素組成的集合(HTMLCollection),由於若是方法的執行主體是集合,瀏覽器一樣會報錯:api

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    </head>
    <body>
        <div class="test" custom="hello"></div>
        <div class="test" custom="hi"></div>
        <script type="text/javascript">
            var div = document.getElementsByClassName('test');
            //獲取的div是[object HTMLCollection]
            alert(div.attr('custom'));
        </script>
    </body>
</html>
正確使用方式:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    </head>
    <body>
        <div class="test" custom="hello"></div>
        <div class="test" custom="hi"></div>
        <script type="text/javascript">
            var div = $('.test');
            //獲取的div是[object object]
            alert(div.attr('custom'));
        </script>
    </body>
</html>
相關文章
相關標籤/搜索