gpt4 book ai didi

javascript - 如何确定使用哪个实例创建了 HTML 元素?

转载 作者:行者123 更新时间:2023-11-29 15:35:48 25 4
gpt4 key购买 nike

var myElement = function(){
this.element = document.createElement('div');
}

var myNewElement = new myElement;
console.log(myNewElement instanceof myElement); //return true

var myDiv = myNewElement.element;
console.log(myDiv instanceof myElement); //return false

是否有可能确定 myDiv 是从 myElement 函数创建的?

最佳答案

与@Felix 所说的相同,

像这样的东西怎么样using data attributes :

var myElement = function(){
this.element = document.createElement('div');
this.element.dataset.instanceof = myElement;
//document.body.appendChild(this.element);
}

var myNewElement = new myElement;
console.log(myNewElement instanceof myElement); //return true

var myDiv = myNewElement.element;
console.log(myDiv.dataset.instanceof == myElement); //return true

这将导致 HTML 元素看起来像这样(如果 appendChild() 未注释):

<div data-instanceof="function (){
this.element = document.createElement('div');
this.element.dataset.instanceof = myElement;
document.body.appendChild(this.element);
}"></div>

或者不是分配整个函数,而是使用这样的字符串:

var myElement = function(){
this.element = document.createElement('div');
this.element.dataset.instanceof = "myElement";
}

var myNewElement = new myElement;
console.log(myNewElement instanceof myElement); //true

var myDiv = myNewElement.element;
console.log(myDiv.dataset.instanceof == "myElement"); //true

关于javascript - 如何确定使用哪个实例创建了 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com