jQuery clearinterval / stopinterval 不起作用

jQuery clearinterval / stopinterval doesn't work

本文关键字:不起作用 stopinterval clearinterval jQuery      更新时间:2023-09-26

我有一个自动刷新功能,如果选中复选框并单击按钮,则会调用该功能。我想在取消单击复选框时停止自动刷新:

var refreshId = null; 
$("#disINFRAlive").click(function(infralivefun) {
    event.preventDefault(infralivefun);
    var category_id = {};
    category_id['datumanf'] = $("#datumanf").datepicker().val();
    category_id['datumend'] = $("#datumend").datepicker().val();
    $.ajax({ //create an ajax request to display.php
        type: "POST",
        url: "infratestomc.php?id=" + Math.random(),
        dataType: "html",      
        data: category_id,
        success: function(response) {
            $("#resulttabelle").show().html(response);
        }
    });
    if ($('#autorefcheck').is(':checked')) {
        var refreshId = setInterval(function() {
            var category_id = {};
            category_id['datumanf'] = $("#datumanf").datepicker().val();
            category_id['datumend'] = $("#datumend").datepicker().val();
            $.ajax({ //create an ajax request to display.php
                type: "POST",
                url: "infratestomc.php?id=" + Math.random(), 
                dataType: "html",
                data: category_id,
                success: function(response) {
                    $("#resulttabelle").show().html(response);
                }
            });
        }, 5000);
    }
});

如果选中复选框 #autorefcheck 并单击按钮 #disINFRAlive,则自动刷新将起作用。但是,我无法通过取消选中复选框来停止它:

function stopinterval(){
  clearInterval(refreshId); 
  return false;
}
$('#autorefcheck').click(function() {
    stopinterval();
});

我尝试以各种方式使用 clearInterval,但到目前为止都没有奏效。

refreshId 的初始化中删除 var 关键字。

if ($('#autorefcheck').is(':checked')) {
    refreshId = setInterval(function() {

拥有它的方式,你在不同的范围内重新声明变量。这样,您将无法从 stopInterval() .