For example, set the class attribute.
Copy codeThe Code is as follows: el. setAttribute ('class', 'abc ');
In IE6/7, the style "abc" does not work, although the value "abc" can be obtained using el. getAttribute ('class ".
Another example is for attributes.Copy codeThe Code is as follows: <label> name: </label> <input type = "checkbox" id = "name"/>
<Script>
Var lab = document. getElementsByTagName ('label') [0];
Lab. setAttribute ('for', 'name ');
</Script>
We know that when the for attribute is set for lab, clicking label will automatically select the corresponding checkbox. However, when you click IE6/7, the checkbox is not selected.
Similar cases occur on cellspacing/cellpadding. Summary:
Class
For
Cellspacing
Cellpadding
Tabindex
Readonly
Maxlength
Rowspan
Colspan
Usemap
Frameborder
Contenteditable
Therefore, when writing a common cross-browser interface method for setting element attributes, you must consider the particularity of the preceding attributes in IE6/7. As follows:Copy codeThe Code is as follows: dom = (function (){
Var fixAttr = {
Tabindex: 'tabindex ',
Readonly: 'readonly ',
'For': 'htmlfor ',
'Class': 'classname ',
Maxlength: 'maxlength ',
Cellspacing: 'cellspacing ',
Cellpadding: 'cellpadding ',
Rowspan: 'rowspan ',
Colspan: 'colspan ',
Usemap: 'usemap ',
Frameborder: 'frameborder ',
Contenteditable: 'contenteditable'
},
Div = document. createElement ('div ');
Div. setAttribute ('class', 'T ');
Var supportSetAttr = div. className = 'T ';
Return {
SetAttr: function (el, name, val ){
El. setAttribute (supportSetAttr? Name: (fixAttr [name] | name), val );
},
GetAttr: function (el, name ){
Return el. getAttribute (supportSetAttr? Name: (fixAttr [name] | name ));
}
}
})();
First, the standard browser uses the original attribute name directly. Second, the attributes not listed above in IE6/7 still use the original attribute name. Finally, these special attributes (with the same name as the JS keyword, such as for and class) use fixAttr.
Now, you don't need to consider className/htmlFor. You can use class/.Copy codeThe Code is as follows: dom. setAttr (el, 'class', 'red ');
Dom. getAttr (el, 'class ');
Dom. setAttr (el, 'for', 'username ');
Dom. getAttr (el, 'for ');