简体   繁体   English

HTML DOM元素是否通过引用存储在Javascript数组中?

[英]Are HTML DOM elements stored by reference in Javascript array?

I have a custom JavaScript object and I want it to be "linked" with an element from the DOM. 我有一个自定义JavaScript对象,我希望它与DOM中的元素“链接”。

var my_object = {}
var element = document.getElementsByClassName("a_class")[7];
my_object["element"] = element;

As I will need many of these objects, I wondered if directly storing DOM object obtained from .getElement() was a good idea? 因为我需要很多这些对象,我想知道直接存储从.getElement()获得的DOM对象是一个好主意吗?

I am scared that this will construct heavy objects. 我很害怕这将构造重物。 Is it the case, or does Javascript use some kind of clever and light references? 是这样的,还是Javascript使用某种聪明和轻量的参考?

Alternatively, I thought to add a custom id to the element before stroring this id but this is less convenient. 或者,我想在调整此id之前向元素添加自定义id ,但这不太方便。

Yes, if you store an HTML DOM element into an object, you are storing its reference. 是的,如果将HTML DOM元素存储到对象中,则存储其引用。

This is good practice because imagine if you have to access an element multiple times, rather than finding that element every single time, get it once and store it. 这是一种很好的做法,因为想象一下,如果你必须多次访问一个元素,而不是每次都找到那个element ,那就得到它一次并存储它。

The process of finding an element is a lot less efficient compared to retrieving it through an object , especially if you use jQuery . 与通过object检索element相比,查找element的过程效率低得多,尤其是在使用jQuery

It does not take up a lot of memory, but this doesn't mean you should be storing every single HTML element on your page in an object . 它不占用大量内存,但这并不意味着您应该将页面中的每个HTML element存储在一个object

Javascript just saves it as a reference. Javascript只是将其保存为参考。

The object is not dereferenced until you retrieve data. 在检索数据之前,不会取消引用该对象。

Like console.log([reference to dereference and log]) console.log([reference to dereference and log])

There is no slow down until the data is dereferenced 在取消引用数据之前不会减速

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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