Javascript重新加载Div冲突

Javascript Reload Div Conflict

本文关键字:Div 冲突 加载 新加载 Javascript      更新时间:2023-09-26

我想通过JavaScript刷新div。我能应付,但我的结构比这更复杂。

如果用户单击一个按钮,就会出现一个新的div。之后,这个div应该每3秒重新加载一次。这些部件还可以。问题是,当用户单击另一个按钮时,系统会重新加载旧的div。例如,用户首先单击按钮Nr 1,然后它会打开,并开始每3秒重新加载一次。然后用户点击按钮Nr 2,它打开,但按钮Nr 1的div在3秒后重新加载。

你可以在下面找到我的代码:

function refreshDiv(id){
    $.ajax({
        url: '<?php echo site_url('canli'); ?>/' + id,
        type: "GET",
        data : "",
        success: function(data) {
            if (data != null)
                $("#matchDetails").html(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
}
$('.livemenumatch').click(function() { 
    clearInterval(refreshIntervalId);
    var id = $(this).attr('data-id');
    localStorage.setItem("lastid", id);
    $.ajax({
        url: 'http://localhost/modo/li/' + id,
        type: 'POST',
        data: { 'submit': true },
        success: function(data) {
            $("#matchDetails").html(data);
        },
    }); 
    var lastid = localStorage.getItem('lastid', lastid);
    var refreshIntervalId = setInterval(function() {
        refreshDiv(lastid)
    }, 3000);  
});

我试着在点击按钮后清除间隔,但没有任何变化。提前谢谢。

问题是因为保存intervalrefreshIntervalId变量设置在单击处理程序的范围内。这意味着,当您单击按钮#2时,变量不包含任何内容,并且不会清除上一个间隔。您需要在更高的范围中声明间隔变量。试试这个:

var refreshIntervalId; // delcare the variable here...
$('.livemenumatch').click(function() { 
    clearInterval(refreshIntervalId);
    // rest of your code... 
    refreshIntervalId = setInterval(function() {
        refreshDiv(id)
    }, 3000);  
});

然而,请注意,使用setInterval()的更好模式是在每次成功完成请求后调用setTimeout()。这意味着,如果每个请求的时间超过3秒,它们就不会被备份并淹没服务器。

function refreshDiv() {
    var id = localStorage.getItem('lastid');
    $.ajax({
        url: '<?php echo site_url('canli'); ?>/' + id,
        type: "GET",
        data : "",
        success: function(data) {
            if (data != null)
                $("#matchDetails").html(data);
            setTimeout(refreshDiv, 3000);
        },
        error: function (data) {
            console.log(data);
        }
    });
}
$('.livemenumatch').click(function() { 
    var id = $(this).attr('data-id');
    localStorage.setItem('lastid', id);
    $.ajax({
        url: 'http://localhost/modo/li/' + id,
        type: 'POST',
        data: { 'submit': true },
        success: function(data) {
            $("#matchDetails").html(data);
        },
    });  
});