문제

The problem is this: when you turn the checkbox, a timer is on, turn off the checkbox and timer goes off. I've tried, but nothing try.

        $('#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>
도움이 되었습니까?

해결책

You have to declare variable outside. like

var timerId = 0;

and then put your code

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);}

});

cause if it's declared inside if then accessing variable timerId from else will not be possible, cause its undefined.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top