custom属性仅适用于element.getAttribute(" attribute"),但不适用于“element.attribute”; [英] custom attribute works only with element.getAttribute("attribute") but not "element.attribute"

查看:178
本文介绍了custom属性仅适用于element.getAttribute(" attribute"),但不适用于“element.attribute”;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<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");

它将返回custom_attr_text,但如果我这样做

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

document.getElementById("my_button").custom_attr;

然后返回 undefined

我还注意到内置属性(例如 value id )以上两种工作都很好!
有人可以解释为什么会发生这种情况吗?

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

推荐答案

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

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-.

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

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

Then they become available in HTML5 compliant browsers as:

element.dataset.custom_attr

但是在遗产中浏览器,你仍然需要使用 .getAttribute()

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

这篇关于custom属性仅适用于element.getAttribute(&quot; attribute&quot;),但不适用于“element.attribute”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆