Car*_*gry 2 html javascript jquery
<span id="ccc">10</span> <span id="start">start</span> <span id="stop">stop</span>
$('#start').click(function(){
var c = $('#ccc').text();
var inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function(){
clearInterval(inter);
});
Run Code Online (Sandbox Code Playgroud)
如何重写这个以正确使用STOP?
inter需要在两个功能范围内.使用闭包来包装这两个函数,以便您可以避免使用新变量污染全局命名空间.
(function ($) {
var inter;
$('#start').click(function(){
var c;
c = parseInt($('#ccc').text()); //make sure you're getting a numeric value
//don't forget to clear any existing interval before setting a new one:
if (inter) {
clearInterval(inter);
}
inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function() {
clearInterval(inter);
});
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2140 次 |
| 最近记录: |