如何在使用Jquery / Javascript找到元素后运行一次函数

时间:2016-02-05 12:31:40

标签: javascript jquery

有没有办法在找到特定元素后运行一次函数?

我试过了:

setInterval(function () {
     if ($('.imagewrapper').length) {
            self.carousel();
     }    
}, 1000)

因此,如果.imagewrapper元素存在,它会持续检查我的页面,如果存在,它应该运行self.carousel()函数。问题是,通过这种方式,一旦元素存在,它就会不断地运行该函数。有办法吗?

ps:setInterval - 方法需要在那里。

3 个答案:

答案 0 :(得分:3)

尝试:

(function delay() {
   if ($('.imagewrapper').length) {
       self.carousel();
   } else {
       setTimeout(delay, 1000);
   }
})();

或者如果你需要setInterval:

var interval = setInterval(function() {
   if ($('.imagewrapper').length) {
       self.carousel();
       clearInterval(interval);
   }
}, 1000);

答案 1 :(得分:1)

很简单:

// 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)

答案 2 :(得分:1)

您正在寻找waitUntilExists https://gist.github.com/buu700/4200601 所以,它会有类似的东西:

$(someselect).waitUntilExists(function(){
    var that = $(this);
    // do some code
})