javascript 自定义属性仅适用于 element.getAttribute("attribute") 但不适用于 "element.attribute"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15010981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:09:29  来源:igfitidea点击:

custom attribute works only with element.getAttribute("attribute") but not "element.attribute"

javascriptgetattributecustom-attribute

提问by Isti115

I have just noticed, that if I give a custom attribute to an html element, for example:

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

<input type="button" id="my_button" custom_attr="custom_attr_text" value="value_text" />

then i can retrieve it like this:

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

document.getElementById("my_button").getAttribute("custom_attr");

and it will return "custom_attr_text", but if I do

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

document.getElementById("my_button").custom_attr;

then it returns undefined!

然后它返回undefined

I also noticed that with a built in attribute (for example valueor id) both of the above works fine! Could somebody please explain why is this happening?

我还注意到,使用内置属性(例如valueid),以上两个都可以正常工作!有人可以解释为什么会发生这种情况吗?

回答by the system

Only certain standard attributes are directly mapped to properties. This is not the defined behavior for non-standard (custom) attributes.

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

The forward compatible way of using custom attributes is to prefix them with data-.

使用自定义属性的向前兼容方式是在它们前面加上data-.

<input ... data-custom_attr="custom_attr_text" ... />

Then they become available in HTML5 compliant browsers as:

然后它们在符合 HTML5 的浏览器中可用:

element.dataset.custom_attr

But in legacy browsers, you'll still need to use .getAttribute().

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