2010-08-17 88 views
0

我已經得到了一些我正在努力的代碼的一些很好的幫助。希望有人能再次幫助我。我的代碼在點擊後的5秒後顯示一個複選標記。問題:如果用戶快速點擊鏈接,我需要取消彈出的複選標記。這裏的演示:jQuery超時問題

www.jontakiff.com/checks

下面的代碼。我已經得到這一個從幾人一些幫助,但超時仍不能正常工作:

$(function() { 

    var thetimeout=null; 
    $('li a').click(function() { 
      $('li').not('this').css('background-position','left bottom'); 
      $(this).parent().css('background-position','left top'); 
      if(thetimeout!=null) { 
       window.clearTimeout(thetimeout); 
      } 
      var thetimeout=window.setTimeout($.proxy(function() { 
        $(this).parent().css('background-image','url(images/check.png)'); 
       }, this) 
      ,5000); 
    }); 

}); 

的clearTimeout應該取消超時所有未點擊的元素,但它不工作...任何想法?

回答

1

您設置的超時在本地存在於點擊事件中 - 因此在每個點擊事件中都存在它自己的超時。

移動var thetimeout之前你$('li').click,然後單擊事件中只使用thetimeout=(具有另一個變種這裏定義了在局部範圍內一個新的變量,而不是使用前一個)。

另外根據你的使用情況,您可能要檢查,看是否超時已經不叫clearTimeout(thetimeout)後設置新的,以及一直存在之前if (!thetimeout)你應該做thetimeout = null否則變量可能仍有價值。

由於上述建議可能會留有餘地的混亂,這裏是連接代碼應用了建議:

$(function() { 

    // Define our Timeout 
    var thetimeout=null, 
     clearTheTimeout = function(){ 
      if (thetimeout) { 
       window.clearTimeout(thetimeout); 
      } 
      thetimeout = null; 
     }; 

    // Do our Click 
    $('li a').click(function() { 
     $('li').not('this').css('background-position','left bottom'); 
     $(this).parent().css('background-position','left top'); 

     // Clear the Timeout 
     clearTheTimeout(); 

     // Set the Timeout 
     thetimeout = window.setTimeout(
      $.proxy(function(){ 
       $(this).parent().css('background-image','url(images/check.png)'); 
       clearTheTimeout(); 
      },this) 
     ,5000); 
    }); 

}); 
+0

我意識到我有代碼在那裏的錯誤編輯...添加if語句。我會嘗試你的建議 – Johnny 2010-08-17 23:26:42

+0

它的工作原理。謝謝。 – Johnny 2010-08-17 23:33:51