1

问题是这样的:当您打开复选框时,计时器打开,关闭复选框并且计时器关闭。我试过了,但没有任何尝试。

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

1 回答 1

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 是不可能的,导致它未定义。

于 2012-11-11T16:42:03.783 回答