gpt4 book ai didi

javascript - 在 JS 对象中引用 HTML 元素

转载 作者:行者123 更新时间:2023-11-28 07:01:35 24 4
gpt4 key购买 nike

当我使用 JQuerys 动态创建一个元素时:

$("<div>",{id : "list"}).html("hello").appendTo("body");

并使用以下方法创建一个 JS 对象:

var obj = {el : document.querySelector("#list") }

打印时控制台返回以下内容 obj.el正如预期的那样:

<div id="list">hello</div>

现在我可以使用 obj.el.innerHTML = "foo"; 设置内容删除元素后使用:

$("#list").remove();

元素保留在之前创建的对象obj中。打印obj.el仍然返回:<div id="list">hello</div>

首先,为什么会这样?有没有一种方法可以存储对元素的偏好而不存储复杂的嵌套 CSS 选择器,这会减慢速度?

最佳答案

阅读这个我认为可以帮助你的小例子。

// it would be in you code : $("<div>",{id : "list"}).html("hello").appendTo("body");
var obj = {
a : 5
};

// let me create this object to better undersatnding
var obj2 = {
a : 3
};

document.write(obj.a + "<br>"); // 5
document.write(obj2.a + "<br>"); // 3


// it would be in you code :var obj = {el : document.querySelector("#list") }
obj2.a = obj.a; //


document.write(obj2.a + "<br>"); // 5

//it would be in you code : $("#list").remove();
delete obj.a;

// here we still have something for obj2
document.write(obj2.a + "<br>"); // 5

// try again :
obj2.a = obj.a;
document.write(obj2.a + "<br>"); // undefined

在你的情况下,如果你尝试:

$("#list").remove();
var obj = {el : document.querySelector("#list") }

我认为 obj 将是未定义的!

关于javascript - 在 JS 对象中引用 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197448/

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