element.setAttribute element ['attr'] element.attr之间的任何差异 [英] Any diffrence between element.setAttribute element['attr'] element.attr
问题描述
我注意到,javascript有几种方法来设置和获取一个元素的属性。
I notice that javascript have several way to set and get attribute with an element.
我不知道他们之间是否有差异。特别是,有浏览器的问题。
I am not sure is there any diffrence between them. especially, is there cross browser problems.
推荐答案
DOM元素的属性和属性是完全不同的,这个区别是一些混乱。
Properties and attributes of DOM elements are quite different, and this difference is a source of some confusion.
一个问题是,并不是每个属性映射到同名的属性。例如,< input>
元素的值
属性映射到 defaultValue
属性,而值
属性不映射到任何属性(除了旧的IE:见下文)。
One problem is that not every attribute maps to a property of the same name. For example, the value
attribute of an <input>
element maps to the defaultValue
property, while the value
property does not map to any attribute (except in old IE: see below).
您应该使用属性的另一个主要原因是较旧版本的IE(< = 7和更高版本的兼容性模式)实现 getAttribute()
和 setAttribute()
不正确。大多数属性直接映射到IE中的相同命名属性,它具有许多不幸的效果,例如设置事件处理程序属性在IE中无法正常工作。以下页面有一些有用的信息: http://reference.sitepoint.com/javascript/Element/setAttribute
The other major reason why you should use properties is that older versions of IE (<=7 and compatibility modes in later versions) implement getAttribute()
and setAttribute()
incorrectly. Most attributes are mapped directly to identically-named properties in IE, which has a number of unfortunate effects such as meaning that setting an event handler attribute does not work correctly in IE. The following page has some useful information: http://reference.sitepoint.com/javascript/Element/setAttribute
还有其他差异。例如,处理URL的属性/属性在处理相对URL方面有一些差异。
There are other differences. For example, attributes/properties that deal with URLs have some discrepancies in how relative URLs are handled.
要查看符合标准的浏览器中的属性和属性之间的区别,请考虑文本框的值:
To see the difference between attributes and properties in standards-compliant browsers, consider the value of a text box:
<input type="text" id="textbox" value="foo">
var textBox = document.getElementById("textbox");
console.log(textBox.getAttribute("value")); // "foo"
console.log(textBox.value); // "foo"
console.log(textBox.defaultValue); // "foo"
现在,如果用户键入文本框或文本框的值更改使用脚本,我们看到属性和属性值分歧:
Now, if the user types into the text box or the text box's value is changed using script, we see the property and attribute values diverge:
textBox.value = "bar";
console.log(textBox.getAttribute("value")); // "foo"
console.log(textBox.value); // "bar"
console.log(textBox.defaultValue); // "foo"
设置属性值现在对当前值不起作用: p>
Setting the attribute value will now have no effect on the current value:
textBox.setAttribute("value", "baz");
console.log(textBox.getAttribute("value")); // "baz"
console.log(textBox.value); // "bar"
console.log(textBox.defaultValue); // "baz"
这篇关于element.setAttribute element ['attr'] element.attr之间的任何差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!