简体   繁体   English

使用 JavaScript 的 HTMLCollection 更改事件

[英]HTMLCollection change event with JavaScript

If I'm assuming correctly, an HTMLCollection is dynamic.如果我假设正确,HTMLCollection 是动态的。

In which changes automatically, as items, are added or removed from the document.其中更改作为项目自动添加或从文档中删除。

Is there a way to detect a change in the size of an HTMLCollection using an event handler?有没有办法使用事件处理程序检测 HTMLCollection 大小的变化? Besides using a timer to constantly poll the collection of course.当然,除了使用计时器不断轮询集合之外。

Just to avoid confusion, dynamic means that something is modified during the runtime.为了避免混淆,动态意味着在运行时修改了某些内容。 HTMLCollection is live , which means it is dynamic plus it can be changed not just by the client script, but also by browser algorithms as declared here . HTMLCollection 是实时的,这意味着它是动态的,而且它不仅可以通过客户端脚本进行更改,还可以通过此处声明的浏览器算法进行更改。 These algorithms can be intercepted by MutationObserver (which is cross-browser today) explained by the test code below:这些算法可以被MutationObserver (今天是跨浏览器)拦截,下面的测试代码解释:

 function addItem() { var li = document.createElement("li"); li.innerHTML = "item"; list.appendChild(li); } var data = list.children; function watch(data) { console.log(data); } var observer = new MutationObserver(watch); observer.observe(list, {childList: true});
 <ul id="list"></ul> <button onclick="addItem()">Add item</button> <button onclick="console.log(data.length)">Test</button>

Here the data is the live HTMLCollection created during the load phase (before DOMContentLoaded fires), but modified by the browser algorithms anytime the Add Item button is pressed (it can be verified by Test button).这里的data是在加载阶段(在 DOMContentLoaded 触发之前)创建的实时 HTMLCollection,但在按下“添加项目”按钮时由浏览器算法修改(可以通过“测试”按钮进行验证)。 The algorithms are intercepted by observer object which calls the watch callback withMutationRecord as its argument.算法被observer对象拦截, observer对象以MutationRecord作为参数调用watch回调。 This can be expensive, so the options need to be set carefully and the observer should be disconnected when not needed.这可能很昂贵,因此需要仔细设置选项,并且在不需要时应断开观察者的连接。

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

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