jQuery clearinterval / stopinterval 不起作用

jQuery clearinterval / stopinterval doesn't work

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

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,并且 none 目前有效。

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

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

按照您的方式,您是在不同的范围内重新声明变量。这样,您就无法从 stopInterval().

访问它