如何等待一个元素存在? [英] How to wait until an element exists?

查看:102
本文介绍了如何等待一个元素存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发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()

这篇关于如何等待一个元素存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆