custom属性仅适用于element.getAttribute("attribute")但不适用于"element.attribute"

Ist*_*115 9 javascript custom-attribute getattribute

我刚才注意到,如果我给html元素一个自定义属性,例如:

<input type="button" id="my_button" custom_attr="custom_attr_text" value="value_text" />
Run Code Online (Sandbox Code Playgroud)

然后我可以像这样检索它:

document.getElementById("my_button").getAttribute("custom_attr");
Run Code Online (Sandbox Code Playgroud)

它会回来"custom_attr_text",但如果我这样做

document.getElementById("my_button").custom_attr;
Run Code Online (Sandbox Code Playgroud)

然后它回来了undefined!

我还注意到,使用内置属性(例如valueid)以上两种工作都很好!有人可以解释为什么会这样吗?

the*_*tem 18

只有某些标准属性直接映射到属性.这不是非标准(自定义)属性的已定义行为.

使用自定义属性的向前兼容方式是为它们添加前缀data-.

<input ... data-custom_attr="custom_attr_text" ... />
Run Code Online (Sandbox Code Playgroud)

然后,它们在HTML5兼容的浏览器中可用:

element.dataset.custom_attr
Run Code Online (Sandbox Code Playgroud)

但在旧版浏览器中,您仍需要使用.getAttribute().