简体   繁体   中英

How to add a property to an element method?

The code looks like document.getElementById.a = 1 . This works except in IE. As the document says

the function is also an object

so it can be added properties, right?

In Javascript you can set or get properties on any value unless :

It is usually bad practice to add properties to native objects/methods because doing so may conflict with other code on the page. I imagine there is a better way to do whatever you are doing.

尝试使用方法setAttribute

document.getElementById('<IDofElement>').setAttribute('a',1);

You can add 'a' to Function prototype. Then it will be available for all Functions.

Function.prototype.a = 1;
console.log(document.getElementById.a); //logs 1
console.log(document.getElementsByClassName.a); //also logs 1

This is not the best solution, but should work even on IE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM