替换元素并在jQuery中返回新元素
如何替换jQuery中的元素并返回替换元素而不是删除的元素?
我有以下情况。 我有很多复选框,一旦你点击其中一个复选框,该复选框将被加载图标替换。 一旦发生一些AJAX事件,加载图标将被刻度图标替换。
使用jQuery的replaceWith
,您可以执行以下操作:
$("input[type='checkbox']").click(function() { $(this).replaceWith(""); $.post("somepage.php"); $(this).replaceWith(""); });
但是,这不起作用,因为replaceWith
返回已删除的元素,而不是添加的元素。 所以在AJAX的东西完成后, https://stackoverflow.com/questions/892861/replacing-an-element-and-returning-the-new-one-in-jquery/loading.jpg
将永远留在那里。
有没有什么方法可以在不选择的情况下返回替换元素?
提前致谢。
给加载图像一个类,然后在post回调中,使用该类作为选择器来查找刚刚注入的图像。
$("input[type='checkbox']").click(function() { $(this).replaceWith(""); $.post("somepage.php", function() { $('.loading-image').replaceWith(""); }); });
如果您可能一次运行其中几个,则可以获得最接近的父项,并在搜索该类时将其用作上下文。
编辑 :另一种替代方法,它使用变量来存储新元素,并且无需在函数返回时应用类并搜索新元素。
$("input[type='checkbox']").click(function() { var loading = $(""); $(this).replaceWith(loading); $.post("somepage.php", function() { loading.replaceWith(""); }); });
创建一个元素并将其用作replaceWith的参数:
$('input[type=checkbox]').click(function() { var img = document.createElement('img'); img.src = 'http://sofzh.miximages.com/jquery/loading.jpg'; $(this).replaceWith(img); $.post('somepage.php', function() { $(img).replaceWith(''); }); });
$('input[type=checkbox]').click(function() { var img = document.createElement('img'); img.src = 'http://sofzh.miximages.com/jquery/loading.jpg'; $(this).replaceWith(img); $.post('somepage.php', function() { $(img).replaceWith(''); }); });
您可以使用索引为其指定唯一ID:
$("input[type='checkbox']").click(function() { var index = $("input[type='checkbox']").index(this); $(this).replaceWith(""); $.post("somepage.php"); $('#myLoadingImage'+index).replaceWith(""); });
你的代码不起作用的原因是第一个replaceWith替换了它引用的项。 第二个替换尝试再次替换它,但由于它已经消失,没有什么可以替代。 并且不会显示勾号图标。
你最好的选择是使用tvanfosson建议的后回调函数。
检查一下。
$.fn.replaceWithMod = function(obj) { var $a = $(obj); this.replaceWith($a); return $a; }; var newObj = $('a').replaceWithMod('New Created Object'); $(newObj).css('color','green');
我写了一个小插件来实现类似的结果,因为我希望能够在一行代码中检索新项目的指针。
(function($){ $.fn['overwrite'] = function(target){ $(target).replaceWith(this); return this; } }(jQuery));
用法示例:
$("input[type='checkbox']").click(function() { var $loading = $("").overwrite( this ); $.post("somepage.php", function() { $loading.replaceWith(""); }); });
如果没有必要专门使用replaceWith方法 – 你可以使用与replaceWith相反的replaceAll方法。
请参阅此处的答案:( 回答一年后提出的类似问题) replaceAll将作为参数传递的对象中的每个元素或与传递的选择器匹配的元素替换为匹配元素的参数,并返回匹配的元素(新内容) )。
这样,tvanfosson答案中的编辑(以及Keeper答案中的代码)将如下所示:
$("input[type='checkbox']").click(function() { var loading = $("").replaceAll($(this)); $.post("somepage.php", function() { loading.replaceWith(""); }); });
它只是一条较短的线,但为了简洁起见并包含使用replaceAll()的选项,我认为适合将这个答案添加到这个古老且更常见的问题中。
为什么不制作一个像这样的中间jquery对象?…
$("input[type='checkbox']").click(function() { var insertedElement = $(""); $(this).replaceWith(insertedElement); $.post("somepage.php"); var anotherInsertedElement = $(""); $(this).replaceWith(anotherInsertedElement); //do something with either of the inserted elements });