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>