jQuery指出,在IE6、7下,浏览器的getAttribute()和setAttribute()不能正常获取和设置Attribute的值。

// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
    get: function( elem, name ) {
        var ret;
        ret = elem.getAttributeNode( name );
        return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
            ret.nodeValue :
            undefined;
    },
    set: function( elem, value, name ) {
        // Set the existing or create a new attribute node
        var ret = elem.getAttributeNode( name );
        if ( !ret ) {
            ret = document.createAttribute( name );
            elem.setAttributeNode( ret );
        }
        return ( ret.nodeValue = value + "" );
    }
};

使用实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>atrribute</title>
</head>
<body>
<div id="element" class="divClass"></div>
<div id="test"></div>
<script type="text/javascript">
    // getAttribute, setAttribute, getAttributeNode, setAttributeNode
    var div = document.createElement("div");
    div.setAttribute("className", "t");

    var element = document.getElementById("element"),
        test = document.getElementById("test");

    // 在IE6, IE7中,执行方法getAttribute()、setAttribute()、removeAttribute()时需要传入DOM属性作为参数而不是HTML属性, jQuery用这个方面来判断是否支持setAttribute, getAttribute, 即jQuery.support.getSetAttribute
    if (div.className!=="t") {
        test.innerHTML = element.getAttribute("class");
        test.setAttribute("class", "addDivClass");
    } else { // IE6, IE7
        test.innerHTML = element.getAttributeNode("class").nodeValue;

        var ret = test.getAttributeNode("class");
        if (!ret) {
            ret = document.createAttribute('class');
            test.setAttributeNode(ret);
        }
        ret.nodeValue = "addDivClass";

    }

    // 最后结果
    /*
    <div id="element" class="divClass"></div>
    <div class="addDivClass" id="test">divClass</div>

    */



</script>
</body>
</html>

小渝人儿
1.1k 声望850 粉丝

前端工程师