替换元素并在jQuery中返回新元素 [英] Replacing an element and returning the new one in jQuery

查看:63
本文介绍了替换元素并在jQuery中返回新元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何替换jQuery中的元素并返回替换元素而不是已删除的元素?

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

我有以下情况.我有很多复选框,一旦您单击其中的一个,该复选框将被一个加载图标替换.一旦发生了一些AJAX问题,加载图标将被打勾图标替换.

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.

使用jQuery的 replaceWith ,您将执行以下操作:

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'/>"); 

});

但是,这不起作用,因为replaceWith返回已删除的元素,而不是添加的元素.因此,在AJAX内容完成后,loading.jpg将会永远呆在那里.

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?

谢谢.

推荐答案

给正在加载的图像提供一个类,然后在post回调中,使用该类作为选择器来查找刚刚注入的图像.

Give the loading image a class, then in the post callback, use the class as a selector to find the image you've just injected.

$("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的最接近的父级,并在搜索类时将其用作上下文.

If you may have several of these running at a time, you can get the closest parent of this and use that as the context when searching for the class.

编辑:另一种方法是使用变量存储新元素,并且无需在函数返回时应用类并搜索新元素.

EDIT: Another alternative that uses a variable to store the new element and removes the need to apply the class and search for the new element when the function returns.

$("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'/>");
  });
});

这篇关于替换元素并在jQuery中返回新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆