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

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

问题描述

我正在 Chrome 中开发一个扩展程序,我想知道:找出元素何时存在的最佳方法是什么?使用普通的 javascript,间隔检查直到元素存在,或者 jQuery 是否有一些简单的方法来做到这一点?

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 与其他 DOM 突变事件一起被弃用,因为性能问题 - 推荐的方法是使用 <一个 href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver" rel="noreferrer">MutationObserver 来观察 DOM.不过,它仅在较新的浏览器中受支持,因此当 MutationObserver 不可用时,您应该退回到 DOMNodeInserted.

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.

let observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (!mutation.addedNodes) return

    for (let i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      let node = mutation.addedNodes[i]
    }
  })
})

observer.observe(document.body, {
    childList: true
  , subtree: true
  , attributes: false
  , characterData: false
})

// stop watching using:
observer.disconnect()

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

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