如何等待一个元素存在?

编程入门 行业动态 更新时间:2024-10-15 16:22:45
本文介绍了如何等待一个元素存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

如何等待一个元素存在?

本文发布于:2023-11-04 18:12:50,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!