开发者

Using jQuery replaceWith to replace content of DIV only working first time

开发者 https://www.devze.com 2023-02-11 12:32 出处:网络
I\'m using the following jQuery to pull new data and replace the contents of the DIV listdata $(function(){

I'm using the following jQuery to pull new data and replace the contents of the DIV listdata

$(function(){
$('.refresh').click(function(event) {
    event.preventDefault();

    $.ajax({
        url: "_js/data.php",
        success: function(results){
            $('#listdata').replaceWith(results);
        }
    });
})开发者_C百科;
});

The script is triggered by numerous links on the page, such as:

<a href="" id="update1" class="refresh">Update 1</a>
<a href="" id="update2" class="refresh">Update 2</a>

For some reason the script only works on the first click of a link. Subsequent clicks do not refresh the data.

I've seen various fixes but nothing that I can get working. Any suggestions?


It looks to me like your problem is with using replaceWith.

You're removing the element which matches $('#listdata') on the first call of replaceWith, so subsequent refreshes can't find where the data is supposed to be placed in the document.

You could try something like

 $('#listdata').empty();
 $('#listdata').append(results);

or chained like this

 $('#listdata').empty().append(results);


If you're using replaceWith(), you're replacing #listdata with a brand new element altogether.

If data isn't something like <div id="listdata"></div> then #listdata is disappearing after the replaceWith(). I'm thinking you should probably use html() instead.


You'll need to change the href's on your links to <a href="#">...</a>. This prevents the browser from refreshing when you click the link.

If you're doing things this way, you'll also want to stick a "return false" at the end of the click handler to prevent bubbling.


Try:

$('a.refresh').live('click', function(e) {
    e.preventDefault();

    $.ajax({
        url: '_js/data.php',
        success: function(data) {
            $('#listdata').empty().html(data);
        }
    });
});

If the .refresh anchors are inside the #listdata element, then delegation is a more optimized solution:

var list = $('#listdata');

list.delegate('a.refresh', 'click', function(e) {
    e.preventDefault();

    $.ajax({
        url: '_js/data.php',
        success: function(data) {
            list.empty().html(data);
        }
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号