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

编程入门 行业动态 更新时间:2024-10-27 14:29:26
本文介绍了替换元素并在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中返回新元素

本文发布于:2023-11-10 15:41:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575774.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   元素   新元素   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!