精通Javascript笔记
第五章中设置/获取元素属性的函数:
function attr(elem, name, value) {
// Make sure that a valid name was provided
if ( !name || name.constructor != String ) return '';
// Figure out if the name is one of the weird naming cases
name = { 'for': 'htmlFor', 'class': 'className' }[name] || name;
// If the user is setting a value, also
if ( value != null ) {
// Set the quick way first
elem[name] = value;
// If we can, use setAttribute
if ( elem.setAttribute )
elem.setAttribute(name,value);
}
// Return the value of the attribute
return elem[name] || elem.getAttribute(name) || '';
}
上述函数在设置元素属性,当元素属性为name范围中的值的时候,会为元素这个两个属性(例如"class"元素会有一个“className"属性和"class"属性,前者是由setAttribute设置,另一个为setter设置;
------------------------------------------------------------------------------------------------------------------------
In real life, in 98% of cases DOM properties are used.
You should use attributes in only two cases:
- A custom HTML attribute, because it is not synced to DOM property.
- To access a built-in HTML attribute, which is not synced from the property, and you are sure you need the attribute.
For example,value
inINPUT
.
------http://javascript.info/tutorial/attributes-and-custom-properties
---------------------------------------------------------------------------------------------------------------------------
所以基本上,我们使用"."可以解决大部分问题。不需要去使用标准高的DOM方法了。