如何替换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将永远留在那里。
有没有什么方法可以在不选择替换元素的情况下返回它?
提前谢谢。
发布于 2009-05-21 13:25:12
给加载图像一个类,然后在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'/>");
});
});发布于 2009-05-21 13:16:06
你可以使用索引给它一个唯一的id:
$("input[type='checkbox']").click(function() {
var index = $("input[type='checkbox']").index(this);
$(this).replaceWith("<img src='loading.jpg' id='myLoadingImage" + index + "' alt='loading'/>");
$.post("somepage.php");
$('#myLoadingImage'+index).replaceWith("<img src='tick.jpg' alt='done'/>");
});发布于 2016-05-09 17:43:02
如果不需要特别使用replaceWith方法-您可以使用与replaceWith相反的replaceAll方法。
在这里可以看到答案:(answer to a similar question asked a year later) replaceAll将作为参数传递的对象中的每个元素或与作为参数传递的选择器匹配的元素替换为匹配的元素,并返回匹配的元素(新内容)。
这样,tvanfosson答案中的编辑(以及Keeper答案中的代码)将如下所示:
$("input[type='checkbox']").click(function() {
var loading = $("<img src='loading.jpg' alt='loading' />").replaceAll($(this));
$.post("somepage.php", function() {
loading.replaceWith("<img src='tick.jpg' alt='done'/>");
});
});它只短了一行,但为了简洁,并包括使用replaceAll()的选项,我认为合适地将这个答案添加到这个旧的、更受欢迎的问题中。
https://stackoverflow.com/questions/892861
复制相似问题