PrependTo项目仅在jQuery中一次 [英] PrependTo item only ONCE in Jquery
问题描述
我具有以下DOM树关系
I have the following DOM-tree relationship
<div class="div-class"></div>
<table class="table-class"></table>
<div class="div-class"></div>
<table class="table-class"></table>
我想做的是将.table-class
移到.div-class
内,但是当我使用prependTo('.div-class')
运行jQuery时,会得到以下输出:
What I would like to do is move the .table-class
inside the .div-class
, but when I run jQuery with prependTo('.div-class')
I get the following output:
<div class="div-class">
<table class="table-class"></table> <!-- they get added TWICE -->
<table class="table-class"></table> <!-- they get added TWICE -->
</div>
<div class="div-class">
<table class="table-class"></table> <!-- they get added TWICE -->
<table class="table-class"></table> <!-- they get added TWICE -->
</div>
我只需要在div.class
内部移动.table-class
的第一个/立即出现.有指针吗?
I just need to move the first/immediate occurrence of .table-class
inside that div.class
. Any pointers?
推荐答案
问题是因为您要将.table-class
元素中.
The issue is because you're prepending all the .div-class
elements to all the .table-class
elements at once.
为解决这个问题,您可以在.div-class
元素上使用prepend()
,并向该方法传递一个函数,该函数返回要添加到该元素的元素.试试这个:
To solve this you can use prepend()
on the .div-class
elements, passing the method a function which returns the element to prepend to. Try this:
$('.div-class').prepend(function() {
return $(this).next('table');
});
div {
padding: 10px;
margin: 0 0 10px;
border: 1px solid #C00;
}
table {
height: 20px;
border: 1px solid #0C0;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-class"></div>
<table class="table-class"></table>
<div class="div-class"></div>
<table class="table-class"></table>
这篇关于PrependTo项目仅在jQuery中一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!