[英]A better method to check if an element exists than a `setTimeout` and `.length`
Currently I have a function that clicks an element once it's dynamically generated, the problem is that I'm using something like this: 当前,我有一个函数,可以在元素动态生成后单击它,问题是我使用的是这样的东西:
if($('#element').length){
$('#element').click();
} else {
setTimeout(function(){
$('#element').click();
}, 500);
}
I keep calling this function until the element appears. 我一直调用此函数,直到元素出现。 Is there a better way to keep checking if an element appeared ?
有没有更好的方法来继续检查元素是否出现? I tried using a loop, but I only ended up crashing the browser with an infinite loop
我尝试使用循环,但最终只能通过无限循环使浏览器崩溃
jQuery has a .load()
event which is called when the element and all sub-elements have been completely loaded. jQuery有一个
.load()
事件,当元素和所有子元素已完全加载时将调用该事件。
$( "#element" ).load(function() {
// is completely loaded
});
Note: This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
注意:此事件可以发送到与URL关联的任何元素:图像,脚本,框架,iframe和窗口对象。
If the element is not associated with any above, then it should be loaded on dom .ready()
event . 如果该元素与以上任何元素都不相关,则应在dom
.ready()
event上加载该元素。
You can make use of Mutation Observer API to check when an element has been added. 您可以使用Mutation Observer API来检查何时添加了元素。
var callback = function(mutations) {
// check the mutations and perform whatever you wish to do
}
var observer = new MutationObserver(callback);
// provide the node that you wish to observe for mutations and the configuration to use
observer.observe(<targetNode>, <config>);
...
...
observer.disconnect();
Edit : Added fiddle as an example where each dynamically added paragraph is echoed as an alert when it's added to the DOM. 编辑 :以小提琴为例,其中每个动态添加的段落在添加到DOM时都会作为警报回显。
jsFiddle - echo dynamically added paragraphs with Mutation Observer API jsFiddle-使用Mutation Observer API回显动态添加的段落
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.