2012-11-11 49 views
1

問題是這樣的: 當您打開復選框時,打開計時器,關閉複選框並關閉計時器。我試過了,但沒有嘗試。複選框和SetInterval

 $('#apply').click(function() { 


    if ($('#autoupdate').prop("checked")) { 

      var timerId = setInterval(function() { 
       $.ajax({ 
        type: "post", 
        url: "1.php", 
        cache: false, 
        success: function (html) { 
         $("#result").html(html); 
        } 
       }); 
      }, 1000); 

    } else {clearInterval(timerId);} 

    }); 


Autoupdate: <input type="checkbox" id="autoupdate"> 
<input id="apply" type="submit" value="Apply"> 
<div id="result"></div> 
+0

感謝您的答案,但它不能解決問題,定時器仍然繼續。 – user1816319

回答

2

你必須在外部聲明變量。像

var timerId = 0; 

,然後把你的代碼

var timerId= 0; 
$('#apply').click(function() { 


    if ($('#autoupdate').prop("checked")) { 

      timerId = setInterval(function() { 
       $.ajax({ 
        type: "post", 
        url: "1.php", 
        cache: false, 
        success: function (html) { 
         $("#result").html(html); 
        } 
       }); 
      }, 1000); 

    } else {clearInterval(timerId);} 

}); 

因爲如果它聲明裏面if然後訪問變量的timerId從別的是不可能的,導致其不確定。

+0

感謝您的答覆,但它不能解決問題,計時器仍然繼續。 – user1816319

+0

我保證這個解決方案可行... –