gpt4 book ai didi

javascript - 什么时候需要重新初始化 jQuery 元素

转载 作者:行者123 更新时间:2023-12-01 15:59:17 25 4
gpt4 key购买 nike

在页面加载时,我存储对字段的引用:

var firstNameField = $('input[name=firstName]');

在任何情况下,该引用会变得“陈旧”,这意味着 DOM 中该输入元素的属性或特性可能会发生变化,并且引用它的 jQuery 元素可能会发生变化不再携带正确的值?

换句话说,在什么情况下我需要重新初始化与底层 DOM 元素更改相关的 jQuery 对象?

最佳答案

Are there any cases where that reference would become "stale" meaning attributes or properties of that input element in the DOM could change and the jQuery element referring to it could no longer carry the correct values?

那件事不会发生,不会。 jQuery 只包含一组加工元素。这些是实际的元素,因此如果它们的状态发生变化(例如,属性发生变化等),当您从 jQuery 集中获取那条状态信息时,它将转到实际的 DOM 元素,因此获取当前信息。例如:

const d = $("#target");
console.log("before", d.attr("data-example")); // undefined
// Change it without using jQuery
document.getElementById("target").setAttribute("data-example", "updated");
console.log("after ", d.attr("data-example")); // "updated"
<div id="target"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

可能会发生,但更为罕见的是,该元素可能被替换为不同的元素。在这种情况下,jQuery 将引用 元素,而不是新元素:

const s = $("#wrapper span");
console.log("before", s.text()); // "This is the initial span"
// Completely replace that span with a different element
$("#wrapper").html("<span>This is the new span</span>");
// The jQuery set is still referring to the old span element
console.log("before", s.text()); // "This is the initial span"
<div id="wrapper">
<span>This is the initial span</span>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

这不是特定于 jQuery 的,如果您只是直接使用该元素也是如此:

const s = document.querySelector("#wrapper span");
console.log("before", s.textContent); // "This is the initial span"
// Completely replace that span with a different element
document.getElementById("wrapper").innerHTML = "<span>This is the new span</span>";
// `s` is still referring to the old span element
console.log("before", s.textContent); // "This is the initial span"
<div id="wrapper">
<span>This is the initial span</span>
</div>

(IE 在这方面有一些奇怪的行为,它会遍历旧元素以清除其文本,但这严重是非标准的,并且 IE 越来越过时。)

DOM 确实提供了一些实时集合,只要您返回该元素的集合,您就会得到新的集合:

const wrapper = document.getElementById("wrapper");
const col = wrapper.getElementsByTagName("span"); // Live collection
console.log("before", col[0].textContent); // "This is the initial span"
// Completely replace that span with a different element
wrapper.innerHTML = "<span>This is the new span</span>";
// `col`'s contents are updated dynamically when the DOM changes
console.log("before", col[0].textContent); // "This is the new span"
<div id="wrapper">
<span>This is the initial span</span>
</div>

您从querySelectorAll 获取的集合(NodeList) 是一个快照,其他大多数是实时集合,例如来自getElementsByTagName 的集合, getElementsByClassName,或元素的childrenchildNodes属性等

关于javascript - 什么时候需要重新初始化 jQuery 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62284009/

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