我正在开发Chrome中的扩展程序,我想知道:元素出现的最佳方式是什么?使用普通的javascript,用一个间隔来检查,直到一个元素存在,或者jQuery有一些简单的方法来做到这一点? 解决方案
由于性能问题, DOMNodeInserted 将被弃用,以及其他DOM突变事件 - 推荐的方法是使用 MutationObserver 观看DOM。它只支持在新的浏览器中,所以当 MutationObserver 不可用时,您应该回到 DOMNodeInserted p>
var observer = new MutationObserver(function(mutations){ mutations.forEach(function如果(!mutation.addedNodes)返回 for(var i = 0; i< mutation.addedNodes.length; i ++){ // // do something到你在这里添加的节点 var node = mutation.addedNodes [i] } })}) observer.observe(document。 body,{ childList:true ,subtree:true ,attributes:false ,characterData:false }) //停止观看使用: observer.disconnect()
I'm working on an Extension in Chrome, and I'm wondering: what's the best way to find out when an element comes into existence? Using plain javascript, with an interval that checks until an element exists, or does jQuery have some easy way to do this?
解决方案DOMNodeInserted is being deprecated, along with the other DOM mutation events, because of performance issues - the recommended approach is to use a MutationObserver to watch the DOM. It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.
var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (!mutation.addedNodes) return for (var i = 0; i < mutation.addedNodes.length; i++) { // do things to your newly added nodes here var node = mutation.addedNodes[i] } }) }) observer.observe(document.body, { childList: true , subtree: true , attributes: false , characterData: false }) // stop watching using: observer.disconnect()
更多推荐
如何等待一个元素存在?
发布评论