JQuery:用另一组替换元素集的优雅方式? [英] JQuery: elegant way to replace set of elements with another set?
问题描述
我有一堆DOM喜欢
< div>
< div class =stuff/>
< div class =stuff/>
< div class =stuff/>
< / div>
我想用一套新东西替换它
< div>
< div class =stuff/>
< p class =stuff/>
< ul class =stuff/>
< a class =stuff/>
< / div>
将通过Ajax获取。我的问题是:这样做的最佳方法是什么?
$ .replaceWith
不是很好我想,因为我最终得到了新的东西
的多个副本。
我可以保证所有东西
都在一个连续的区块中,所以我想可以放入一些占位符在旧 stuff
的最后一个元素之后(或第一个元素之前),删除旧的 stuff
,并替换带有新东西的占位符
。
然而,这似乎相当迂回而且不优雅。是否有任何聪明的方法,删除所有旧的东西
并放入新的东西的单个副本
,所有一气呵成?
编辑:我也想在不使用任何容器div的情况下这样做。使用容器div可以在上面的情况下工作,但在某些情况下会失败,例如当 stuff
在< table> $内时c $ c>:
< table>
< head />
< body>
< tr />
< tr class =stuff/>
< tr class =stuff/>
< tr class =stuff/>
< tr />
< / body>
< / table>
如果我想替换标有 stuff
使用另一组行,可能更多,可能更少,在没有破坏HTML的情况下,我无法将它们很好地放入容器中,因为< body>
只能包含< tr>
s(IIRC)。
$( '#outerdiv')空()追加(newContent)。;
与 .html()
不同,这将是无论 newContent
是HTML字符串还是现有的DOM结构,都可以正常工作。
如果有多个元素要被替换,但你需要保留他们的兄弟姐妹,你可以这样做:
$('。stuff')。first( )。之前(newContent).END()除去();
即。取第一个 .stuff
元素,在其前面添加新内容,然后删除所有 .stuff
元素。 / p>
I have a bunch of DOM like
<div>
<div class="stuff"/>
<div class="stuff"/>
<div class="stuff"/>
</div>
and I want to replace it with a new set of stuff
<div>
<div class="stuff"/>
<p class="stuff"/>
<ul class="stuff"/>
<a class="stuff"/>
</div>
Which will be fetched via Ajax. My question is: what is the best way to do this?
$.replaceWith
doesn't quite do what I want, because I then end up with multiple copies of the new stuff
.
I can guarantee that all the stuff
will be in one contiguous block, and so presumably I could put in some placeholder after the last element (or before the first element) of the old stuff
, remove the old stuff
, and replace the placeholder with the new stuff
.
However, this seems rather roundabout and inelegant. Is there any clever way of, removing all the old stuff
and putting in a single copy of the new stuff
, all at one go?
EDIT: I would also like to do this without using any container divs. Using container divs would work in the above case, but would fail in some cases, like when the stuff
is inside a <table>
:
<table>
<head/>
<body>
<tr/>
<tr class="stuff"/>
<tr class="stuff"/>
<tr class="stuff"/>
<tr/>
</body>
</table>
If i want to replace the rows labelled stuff
with another set of rows, possibly more, possibly fewer, there is no way I can nicely put them in a container thingy without breaking the HTML, since the <body>
can only contain <tr>
s (IIRC).
$('#outerdiv').empty().append(newContent);
Unlike .html()
, this will work regardless of whether newContent
is an HTML string, or an existing DOM structure.
If there are multiple elements to be replaced but where you need to retain their siblings, you can do this:
$('.stuff').first().before(newContent).end().remove();
i.e. take the first .stuff
element, add the new content before it, and then remove all the .stuff
elements.
这篇关于JQuery:用另一组替换元素集的优雅方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!