且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

属性的获取

更新时间:2022-09-13 20:42:37

jQuery.attr , Sizzle.attr

属性的获取
Sizzle.attr = function(elem, name) {
    // Set document vars if needed
    if ((elem.ownerDocument || elem) !== document) {
        setDocument(elem);
    }

    var fn = Expr.attrHandle[name.toLowerCase()],
        // Don't get fooled by Object.prototype properties (jQuery #13807)
        val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ?
            fn(elem, name, !documentIsHTML) :
            undefined;

    return val !== undefined ?
        val :
        support.attributes || !documentIsHTML ?
        elem.getAttribute(name) :
        (val = elem.getAttributeNode(name)) && val.specified ?
        val.value :
        null;
};
属性的获取

在IE6 7中getAttribute返回属性而不是属性

属性的获取
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function(div) {
    div.className = "i";
    return !div.getAttribute("className");
});
属性的获取

所以jquery采用getAttributeNode方法处理

获取属性值 - getAttribute() 

getAttribute("") 方法返回属性的值。


获取属性值 - getAttributeNode()

getAttributeNode("") 方法返回属性节点,getAttributeNode('').value取得节点值。
 
 
<li class="aa"></li>
li.getAttributeNode('class')  // class="aa"
li.getAttribute('class') //aa
 
 
特别指出加强specified的判断是因为,在IE6 7会返回所有的节点,只需要返回有用的特性节点

 

本文转自艾伦 Aaron博客园博客,原文链接:http://www.cnblogs.com/aaronjs/p/4112769.html,如需转载请自行联系原作者