如何替换 jQuery 中的元素并返回替换元素而不是被删除的元素?
我有以下场景。我有很多复选框,一旦您单击其中一个,该复选框就会被加载图标取代。一旦发生一些 AJAX 事件,加载图标就会被勾号图标取代。
使用 jQuery 的replaceWith http://docs.jquery.com/Manipulation/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'/>");
});
});
如果您可能同时运行其中几个,您可以获得最接近的父级this
并在搜索类时使用它作为上下文。
EDIT:另一种替代方法是使用变量来存储新元素,并且无需在函数返回时应用类并搜索新元素。
$("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'/>");
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)