javascript 我可以向 DOM 对象添加任意属性吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4258466/
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
Can I add arbitrary properties to DOM objects?
提问by Tony the Pony
Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT>or <SELECT>elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?
我可以向 JavaScript DOM 对象添加任意属性,例如<INPUT>或<SELECT>元素吗?或者,如果我不能这样做,有没有办法通过引用属性将我自己的对象与页面元素相关联?
采纳答案by meder omuraliev
Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.
当然,人们已经这样做了很长时间。不建议这样做,因为它很乱,而且您可能会弄乱现有的属性。
If you are looping code with for..inyour code may break because you will now be enumerating through these newly attached properties.
如果您使用for..in代码循环代码可能会中断,因为您现在将枚举这些新附加的属性。
I suggest using something like jQuery's .datawhich keeps metadata attached to objects. If you don't want to use a library, re-implement jQuery.data
我建议使用类似 jQuery 的东西.data,它可以将元数据附加到对象上。如果您不想使用库,请重新实现jQuery.data
回答by Andy E
Yes, you can add your own properties to DOM objects, but remember to take care to avoid naming collisions and circular references.
是的,您可以将自己的属性添加到 DOM 对象,但请记住要小心避免命名冲突和循环引用。
document.getElementById("myElement").myProperty = "my value";
HTML5 introduced a valid way of attaching data to elements via the markup - using the data-attribute prefix. You can use this method in HTML 4 documents with no issues too, but they will not validate:
HTML5 引入了一种通过标记将数据附加到元素的有效方法 - 使用data-属性前缀。您也可以在 HTML 4 文档中使用此方法而不会出现问题,但它们不会验证:
<div id="myElement" data-myproperty="my value"></div>
Which you can access via JavaScript using getAttribute():
您可以使用以下方法通过 JavaScript 访问getAttribute():
document.getElementById("myElement").getAttribute("data-myproperty");
回答by James
ECMAScript 6 has WeakMap which lets you associate your private data with a DOM element (or any other object) for as long as that object exists.
ECMAScript 6 具有 WeakMap,只要该对象存在,您就可以将私有数据与 DOM 元素(或任何其他对象)相关联。
const wm = new WeakMap();
el = document.getElementById("myelement");
wm.set(el, "my value");
console.log(wm.get(el)); // "my value"
Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.
与其他答案不同,此方法保证永远不会与任何属性或数据的名称发生冲突。
回答by morris4
回答by mikefrey
Do you want to add properties to the object, or attributes to the element?
您要向对象添加属性,还是要向元素添加属性?
You can add attributes using setAttribute
您可以使用添加属性 setAttribute
var el = document.getElementById('myelement');
el.setAttribute('custom', 'value');
or you can just add properties to the javascript object:
或者您可以只向 javascript 对象添加属性:
var el = document.getElementById('myelement');
el.myProperty = 'myValue';
回答by bcosca
If you must, don't use standard HTML attributes. Here's a tutorial on using custom attributes:
如果必须,请不要使用标准的 HTML 属性。这是有关使用自定义属性的教程:
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml
It's HTML5, but it's backward-compatible.
它是 HTML5,但它是向后兼容的。
回答by niiima
I was exploring answers and want to add that we can set attributes on domElementswith using datasetproperty, it could use on HTMLOrForeignElement(that's a mixin of several features common to the HTMLElement, SVGElementand MathMLElementinterfaces).
我正在探索答案并想补充一点,我们可以domElements使用 usingdataset属性来设置属性,它可以使用 on HTMLOrForeignElement(这是HTMLElement,SVGElement和MathMLElement接口的几个常见功能的混合)。
According to mdn
根据mdn
The
datasetproperty on the HTMLOrForeignElement interface provides read/write access to all the custom data attributes(data-*)set on the element. This access is available both in HTML and within the DOM. It is a map ofDOMStrings, one entry for each custom data attribute.
在
dataset该HTMLOrForeignElement接口属性提供读取所有的自定义数据写访问属性/(data-*)设置元素上。这种访问在 HTML 和 DOM 中都可用。它是 的映射DOMStrings,每个自定义数据属性一个条目。
let element = document.getElementById("test");
let footer = document.querySelector("#output");
/* get element values using camelCase names through .dataset */
let sample = element.dataset.sample;
let sampleNumber = element.dataset.sampleNumber;
let dataFromElement = sample + " :: " + sampleNumber;
footer.innerHTML = element.innerHTML + dataFromElement;
<input type="hidden" id="test" data-sample="Sample" data-sample-number=34 />
<div id="output"> </div>
Although there are concerns about Internet Explorer support and performance on this you can check here.
尽管对此存在对 Internet Explorer 支持和性能的担忧,但您可以在此处查看。

