简体   繁体   English

点击功能加载后刷新div的内容

[英]Refresh contents of div after loading with click function

I have a page laid out with 2 Div's on the page. 我在页面上布置了2个Div。 The first Div works fine and loads a list of players. 第一个Div工作正常,并加载了玩家列表。 Now when you click on a link in that Div, it loads a second Div with information about that player. 现在,当您单击该Div中的链接时,它将加载第二个Div,其中包含有关该播放器的信息。 That too works fine, but what I want to do is have that second Div periodically refresh that players data after it being loaded by the click event. 那也很好用,但是我想做的是让第二个Div在被click事件加载之后定期刷新播放器数据。 Here was my current attempt but it's not working: 这是我目前的尝试,但是没有用:

var loc = "";
$("a").live('click', function() {
    loc = "player.php?user=" + $(this).html();
    $("#result").load(loc);
});
setInterval(function() {
    $("#results").load(loc);
}, 1000);

Try moving the setInterval inside the click event handler so that it doesn't fire off before the first click and you ensure the loc is defined before the first interval completes. 尝试将setInterval移入click事件处理程序内,以使其在第一次单击之前不会触发,并确保在第一个间隔完成之前定义了loc

Also, you may have a typo within your setInterval , as it refers to $('#results') , not $('#result') . 另外,您可能会在setInterval有一个错字,因为它是指$('#results') ,而不是$('#result') One or the other is likely incorrect. 一个或另一个可能不正确。

Finally, it's good practice to assign a setInterval to a variable, so that you can clear it later, if needed with clearInterval . 最后,优良作法是将setInterval分配给变量,以便以后可以根据需要使用clearInterval清除它。 it also lets you set the interval just once, rather than every time the user clicks 它还可以让您只设置一次间隔,而不是每次用户单击时都设置一次

var loc = "";
var interval = null;

$("a").live('click', function(){
    loc = "player.php?user=" + $(this).html();

    $("#result").load(loc);

    // only create the interval once
    if(!interval) {
        interval = setInterval(function(){
            $("#result").load(loc);
        }, 1000);
    }
});

You are assigning the url to loc in click event of anchor a which would be loading the contents but the other case of setInterval which is executed on load the loc will not have the url. 您在锚点a click事件中将url分配给loc,该锚事件将要加载内容,但在加载时执行的setInterval的另一种情况下,loc将没有该url。 So assign url to loc the time you declare it or make sure it is assigned before setInterval. 因此,分配url来定位您声明它的时间,或者确保在setInterval之前分配它。

Also note live is deprecated you should use on instead. 另请注意,不建议使用live on而应改用on

var loc = "player.php?user=" + $("a").html();
$("a").live('click', function(){
        loc = "player.php?user=" + $(this).html();
        $("#result").load(loc);
    });
setInterval(function(){
    $("#results").load(loc);
}, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM