Replacing an element and returning the new one in

2020-05-25 07:33发布

How do you replace an element in jQuery and have the replacement element returned instead of the element that was removed?

I have the following scenario. I have many checkboxes and once you click one of them, that checkbox is replaced by a loading icon. Once some AJAX stuff happens, the loading icon is replaced by a tick icon.

Using jQuery's replaceWith, you'd do something like:

$("input[type='checkbox']").click(function() {

  $(this).replaceWith("<img src='loading.jpg' alt='loading'/>");
  $.post("somepage.php");
  $(this).replaceWith("<img src='tick.jpg' alt='done'/>"); 

});

However, this doesn't work because replaceWith returns the element that was removed, not the one which was added. So after the AJAX stuff completes, loading.jpg will just stay there forever.

Is there some way I can return the replacement element without selecting it?

Thanks in advance.

8条回答
Deceive 欺骗
2楼-- · 2020-05-25 08:16

Why not make an intermediate jquery object, like this?...

$("input[type='checkbox']").click(function() {
    var insertedElement = $("<img src='loading.jpg' alt='loading'/>");
    $(this).replaceWith(insertedElement);
    $.post("somepage.php");
    var anotherInsertedElement = $("<img src='tick.jpg' alt='done'/>");
    $(this).replaceWith(anotherInsertedElement);
    //do something with either of the inserted elements
});
查看更多
不美不萌又怎样
3楼-- · 2020-05-25 08:19

Create an element and use it as parameter to replaceWith:


$('input[type=checkbox]').click(function() {
    var img = document.createElement('img');
    img.src = 'loading.jpg';
    $(this).replaceWith(img);
    $.post('somepage.php', function() {
        $(img).replaceWith('<img src="tick.jpg" alt="done"/>');
    });
});

查看更多
登录 后发表回答