PrependTo项目仅在jQuery中一次 [英] PrependTo item only ONCE in Jquery

查看:100
本文介绍了PrependTo项目仅在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?

推荐答案

问题是因为您要将 all 元素同时添加到所有.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆