[英]How to run a function once after element has been found with Jquery/Javascript
找到特定元素后,是否可以通过一种方法来运行函数?
我尝试了这个:
setInterval(function () {
if ($('.imagewrapper').length) {
self.carousel();
}
}, 1000)
因此,它将连续检查我的页面是否存在.imagewrapper
元素,如果存在,则应运行self.carousel()
函数。 问题在于,这样,一旦元素存在,它就会连续运行该功能。 有办法吗?
ps: setInterval
方法必须存在。
尝试:
(function delay() {
if ($('.imagewrapper').length) {
self.carousel();
} else {
setTimeout(delay, 1000);
}
})();
或者如果您需要setInterval:
var interval = setInterval(function() {
if ($('.imagewrapper').length) {
self.carousel();
clearInterval(interval);
}
}, 1000);
这很容易:
// 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)
您正在寻找waitUntilExists https://gist.github.com/buu700/4200601因此,它的工作原理如下:
$(someselect).waitUntilExists(function(){
var that = $(this);
// do some code
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.