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

坚强是说给别人听的谎言 提交于 2019-12-05 05:41:10
Sam Dufel

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);
        }
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!