2012-11-11 55 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

我保证这个解决方案可行... –