在jQuery中替换一个元素并返回新元素

前端之家收集整理的这篇文章主要介绍了在jQuery中替换一个元素并返回新元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何替换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将永远留在这里。

有没有办法可以返回替换元素而不选择它?

提前致谢。

解决方法

给加载图像一个类,然后在后回调中,使用类作为选择器来查找刚刚注入的图像。
$("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'/>");
  });
});

如果您一次可能有几个运行,您可以得到最接近的父项,并在搜索该类时将其用作上下文。

编辑:另一个替代方法是使用变量来存储新的元素,并且消除了在函数返回时应用该类并搜索新元素的需要。

$("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'/>");
  });
});
原文链接:https://www.f2er.com/jquery/183500.html

猜你在找的jQuery相关文章