当我使用 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/