2011-11-05 37 views
0

任何地方我有這樣的jQuery代碼:#fr_tab股利的setInterval的onclick和的點擊明確的文件

$('#fr_tab').click(function() { 
    $("#tab2").empty().html('<img src="images/loading.gif" />'); 
var handle = setInterval(function() { 
    $('#tab2').load('fr_quests.php'); 
    }, 3000); 
    }); 

    $('body').click(function() { 
     if (handle) { 
      clearInterval(handle); 
      handle = 0; 
     } 
    }); 

我在想,當點擊#fr_tab時,我如何能夠setIneterval,我怎麼能在任何地方,如果清除它在文件中被點擊。

回答

1

handle變量是本地第一function。刪除var前綴使其成爲全球化是最快捷的方式,但絕對不是最好的。

另外,不使用全局變量,那麼,如果代碼是在$(文件)。就緒(...)函數然後

$(document).ready(function() { 
     var handle 
     $('#fr_tab').click(function() { 
      $("#tab2").empty().html('<img src="images/loading.gif" />'); 
      handle = setInterval(function() { 
       $('#tab2').load('fr_quests.php'); 
      }, 3000); 
     }); 

     $('body').click(function() { 
      if (handle) { 
       clearInterval(handle); 
       handle = 0; 
      } 
     }); 
    }); 
0

你將要觸發$(document).not('#tab2').click(...

+0

不清除處理:(。 – re1man

+0

這個代碼在$(document).ready?內? – Will

+0

是的......實際上我會在我的當前代碼中添加 – re1man