简体   繁体   English

从DOM元素获取JavaScript对象

[英]Getting javascript object back from DOM element

Say I create a javascript class as follows: 说我创建一个如下的javascript类:

class DivClass {
  constructor () {
    this.div1 = document.createElement('div')
    this.div1.id = 'div1'
  }
}

Later I instantiate the class as follows: 后来我实例化该类,如下所示:

var divObject = new DivClass()
parentDiv.appendChild(divObject.div1)

and the DIV eventually appears in the DOM. DIV最终出现在DOM中。

If I was to locate the 'div1' element within the DOM, say via getElementById() for argument sake, is there anyway of getting back to the javascript 'divObject' responsible for its creation? 如果我要在DOM中定位“ div1”元素,请通过getElementById()进行参数说明,是否有返回到负责其创建的javascript“ divObject”?

From what little I've learned about javascript, I kind of get the impression that the translation from javascript API to DOM is a one way trip and this just simply isn't possible. 从我对javascript的了解中,我得到的印象是,从javascript API到DOM的转换是一种单程旅行,而这根本是不可能的。

Apologies in advance if I've gotten any of the terminology wrong, but I'm kind of new to javascript and still don't fully understand the DOM/API relationship. 如果我弄错了任何术语,请提前道歉,但是我对javascript还是陌生的,但仍然不能完全理解DOM / API的关系。

Any advice would be greatly appreciated. 任何建议将不胜感激。

You can add a reference to the object to the DIV element. 您可以将对对象的引用添加到DIV元素。

class DivClass {
  constructor () {
    this.div1 = document.createElement('div')
    this.div1.id = 'div1'
    this.div1.divClass = this;
  }
}

Then you can use document.getElementById("div1").divClass to get the object. 然后,您可以使用document.getElementById("div1").divClass来获取对象。

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

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