简体   繁体   中英

Refresh contents of div after loading with click function

I have a page laid out with 2 Div's on the page. The first Div works fine and loads a list of players. Now when you click on a link in that Div, it loads a second Div with information about that player. 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. 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.

Also, you may have a typo within your setInterval , as it refers to $('#results') , not $('#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 . 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. So assign url to loc the time you declare it or make sure it is assigned before setInterval.

Also note live is deprecated you should use on instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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