复选框和SetInterval

时间:2012-11-11 16:39:28

标签: jquery checkbox setinterval clearinterval

问题在于: 当你打开复选框时,计时器打开,关闭复选框,计时器熄灭。我试过了,但没有尝试。

        $('#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>

1 个答案:

答案 0 :(得分: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内声明,则无法从else访问变量timerId,导致其未定义。