[英]How to run a function once after element has been found with Jquery/Javascript
Is there a way I can run a function once after a specific element has been found? 找到特定元素后,是否可以通过一种方法来运行函数?
I tried this: 我尝试了这个:
setInterval(function () {
if ($('.imagewrapper').length) {
self.carousel();
}
}, 1000)
So, it checks my page continiously if the .imagewrapper
element exisit, and if so, it should run the self.carousel()
function. 因此,它将连续检查我的页面是否存在
.imagewrapper
元素,如果存在,则应运行self.carousel()
函数。 The problem is, that this way, as soon the element exists, it runs the function continiously. 问题在于,这样,一旦元素存在,它就会连续运行该功能。 Is there a way around?
有办法吗?
ps: The setInterval
-method needs to be there. ps:
setInterval
方法必须存在。
Try: 尝试:
(function delay() {
if ($('.imagewrapper').length) {
self.carousel();
} else {
setTimeout(delay, 1000);
}
})();
or if you need setInterval: 或者如果您需要setInterval:
var interval = setInterval(function() {
if ($('.imagewrapper').length) {
self.carousel();
clearInterval(interval);
}
}, 1000);
It's easy: 这很容易:
// set ran to false when you load the page
ran = false;
setInterval(function () {
// only do your stuff when you haven't do yet (ran==false)
if (!ran && $('.imagewrapper').length) {
self.carousel();
// when you did it for the 1st time set ran to true, so next time you don't enter the if.
ran = true;
} }, 1000)
// but even better to stop the timer after you entered the if for the 1st time:
timer = setInterval(function () {
// only do your stuff when you haven't do yet (ran==false)
if ($('.imagewrapper').length) {
self.carousel();
// when you did it for the 1st time delete the timer
clearInterval(timer);
} }, 1000)
You looking for waitUntilExists https://gist.github.com/buu700/4200601 So, it will works something like that: 您正在寻找waitUntilExists https://gist.github.com/buu700/4200601因此,它的工作原理如下:
$(someselect).waitUntilExists(function(){
var that = $(this);
// do some code
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.