jQuery:分离并重新附加元素,而无需重新加载内容 [英] jQuery: detach and re-attach element without reloading content
问题描述
我想知道是否有可能使用jQuery分离然后将元素(例如div)重新附加到DOM,而无需重新加载元素中的内容.
I would like to know if it's possible using jQuery to detach and then re-attach an element (e.g. a div) to the DOM without reloading the content within the element.
考虑以下示例布局:
<div class="row">
<div class="col-lg-6">
<div class="card">
<img src="something.jpg" />
</div>
<div class="card">
<img src="something.jpg" />
</div>
<div class="card">
<iframe src="example.com" id="widget">
</div>
</div>
<div class="col-lg-6">
<div class="card">
<!-- User hides this card -->
<img src="something.jpg" />
</div>
<div class="card">
<iframe src="example.com" id="widget">
</div>
</div>
</div>
第一列有3张卡片,第二列有2张卡片.如果用户在第二列中隐藏了其中一张卡,我想通过将其中一张卡从第一列移动到第二列来重新堆叠卡,以便现在每列中有两张卡.我可以很容易地使用.detach()
和.appendTo()
来完成此操作,但是当我将卡从第一列重新连接到第二列时,卡中包含的任何内容都会重新加载,无论是图像还是诸如嵌入式的小部件鸣叫.
There are 3 cards in the first column and two in the second column. If the user hides one of the cards in the second column, I want to restack the cards by moving one of the cards from the first column to the second column, so that there are now two cards in each column. I can accomplish this using .detach()
and .appendTo()
easily enough, but when I re-attach the card from the first column to the second, whatever content that card contains is reloaded, be it an image or a widget such as an embedded Tweet.
我想知道的是,是否有可能将卡从一列移到另一列而不会触发其中的内容重新加载.
What I'd like to know is if it's possible to move a card from one column to another without triggering the content within it to be reloaded.
推荐答案
使用.clone()
似乎没有再次请求资源.注意,.detach()
在.appendTo()
之后被调用.
Using .clone()
does not appear to request resource again. Note, .detach()
is called after .appendTo()
.
还请注意,带有document
的元素的id
应该是唯一的; Question的html
中有两个具有id
"widget"
的元素;尝试更改为class="widget"
Note also that id
of element with a document
should be unique; two elements having id
"widget"
are within html
at Question; try changing to class="widget"
$(".col-lg-6:eq(1) div").click(function(e) {
$(e.target).hide();
var clone = $(".col-lg-6:eq(0) div:eq(0)").clone();
clone.appendTo(".col-lg-6:eq(1)");
$(".col-lg-6:eq(0) div:first").detach();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="row">
<div class="col-lg-6">
<div class="card">
<img src="http://lorempixel.com/50/50/nature" />
</div>
<div class="card">
<img src="http://lorempixel.com/50/50/cats" />
</div>
<div class="card">
<iframe src="example.com" class="widget"></iframe>
</div>
</div>
<div class="col-lg-6">
<div class="card">
<!-- User hides this card -->
<img src="http://lorempixel.com/50/50/sports" />
</div>
<div class="card">
<iframe src="example.com" class="widget"></iframe>
</div>
</div>
</div>
这篇关于jQuery:分离并重新附加元素,而无需重新加载内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!