如何替换jQuery中的元素并返回替换元素而不是删除的元素?
我有以下场景.我有很多复选框,一旦你点击其中一个复选框,该复选框就会被一个加载图标取代.一旦发生一些AJAX事件,加载图标将被刻度图标取代.
使用jQuery replaceWith,您可以执行以下操作:
$("input[type='checkbox']").click(function() {
  $(this).replaceWith("<img src='loading.jpg' alt='loading'/>");
  $.post("somepage.php");
  $(this).replaceWith("<img src='tick.jpg' alt='done'/>"); 
});
但是,这不起作用,因为replaceWith返回已删除的元素,而不是添加的元素.因此,在AJAX的东西完成之后,loading.jpg它将永远留在那里.
有没有什么方法可以在不选择的情况下返回替换元素?
提前致谢.
tva*_*son 22
给加载图像一个类,然后在post回调中,使用该类作为选择器来查找刚刚注入的图像.
$("input[type='checkbox']").click(function() {
  $(this).replaceWith("<img src='loading.jpg' alt='loading' class='loading-image' />");
  $.post("somepage.php", function() {
      $('.loading-image').replaceWith("<img src='tick.jpg' alt='done'/>");
  });
});
如果您可能一次运行其中几个,则可以获取最接近的父级,this并在搜索该类时将其用作上下文.
编辑:另一种替代方法,它使用变量来存储新元素,并且无需在函数返回时应用类并搜索新元素.
$("input[type='checkbox']").click(function() {
  var loading = $("<img src='loading.jpg' alt='loading' />");
  $(this).replaceWith(loading);
  $.post("somepage.php", function() {
      loading.replaceWith("<img src='tick.jpg' alt='done'/>");
  });
});
Kee*_*per 13
创建一个元素并将其用作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"/>');
    });
});