自定义属性只适用于element.getAttribute(“属性”),而不是“element.attribute”
问题描述:
我刚才注意到,如果我给一个自定义属性的HTML元素,例如:自定义属性只适用于element.getAttribute(“属性”),而不是“element.attribute”
<input type="button" id="my_button" custom_attr="custom_attr_text" value="value_text" />
然后我可以这样获取:
document.getElementById("my_button").getAttribute("custom_attr");
,它将返回"custom_attr_text"
,但如果我不
document.getElementById("my_button").custom_attr;
然后它返回undefined
!
我还注意到,与内置属性(例如value
或id
)上述两个工作正常! 请问有人可以解释为什么会发生这种情况?
答
只有某些标准属性直接映射到属性。这不是非标准(自定义)属性的定义行为。
使用自定义属性的向前兼容方式是以data-
为前缀。
<input ... data-custom_attr="custom_attr_text" ... />
于是,他们在HTML5变得可用兼容的浏览器为:
element.dataset.custom_attr
但在传统的浏览器,你仍然需要使用.getAttribute()
。
这是一个有点jbit特定的,但看到[.prop()与.attr()](http://stackoverflow.com/questions/5874652/prop-vs-attr)的副本。如果你想要一个只有普通的js解释,请参阅http://javascript.info/tutorial/attributes-and-custom-properties – Bergi 2013-02-21 19:53:51