Is there a good way to attach JavaScript objects to HTML elements?

后端 未结 2 1952
情书的邮戳
情书的邮戳 2020-12-04 18:30

I want to associate a JavaScript object with an HTML element. Is there a simple way to do this?

I noticed HTML DOM defines a setAttribute method and it looks like th

相关标签:
2条回答
  • 2020-12-04 19:30

    Have you looked at the jQuery data() method? You can assign complex objects to the element if you want or you can leverage that method to hold a reference to an object (or some other data) at the very least.

    0 讨论(0)
  • 2020-12-04 19:32

    JavaScript objects can have arbitrary properties assigned to them, there's nothing special you have to do to allow it. This includes DOM elements; although this behaviour is not part of the DOM standard, it has been the case going back to the very first versions of JavaScript and is totally reliable.

    var div= document.getElementById('nav');
    div.potato= ['lemons', 3];
    
    0 讨论(0)
提交回复
热议问题