javascript - 使用 jQuery 在单击时复制特定结构

标签 javascript jquery html css

这就是我所拥有的:

HTML

<div class="table-product-wrap-inner">
  <table class="table-product">
    <tbody>
      <tr>
        <td></td>
        .........
        <td>
          <buttom class="btn-copy-link"></button>
        </td>
      </tr>
    </tbody>
  </table>
  <button class="dont-copy-that-btn></button>
  <div class="collapse"></div>
</div>

jQ

init: function () {
      var that = this;

      this.$productEdit.on('click', '.btn-copy-link', function(){
          var $cTable = $(this).closest('.table-product'),
              $ele = $cTable.clone(true),
              $gName = $ele.find('td:first'),
              $lName = $ele.find('.product-link-title'),
              $idL = $ele.find('.product-link-id');

          $cTable.after($ele);
          $gName.empty();
          $lName.val($lName.val() + " Копия");
          $idL.val('');
        });
}

当前函数复制最近的 table 并将其插入到原始文件之后,但我还需要复制最近的 divcollapse 和 past table + div 之后 collapse。复制位于 table 中的 button

像这样:

<div class="table-product-wrap-inner">
  <table class="table-product">
    <button class="btn-copy-link"></button>
  </table>
  <button class="dont-copy-that-btn></button>
  <div class="collapse"></div>
</div>

点击后:

<div class="table-product-wrap-inner">
   <table class="table-product">
     <button class="btn-copy-link"></button>
   </table>
   <button class="dont-copy-that-btn></button>
   <div class="collapse"></div>
   <!-- COPY-->
   <table class="table-product">
     <button class="btn-copy-link"></button>
   </table>
   <div class="collapse"></div>
 </div>

如果用户在第一对 table + div 中再次单击 button,它将在该对之后复制它们。如果我们在第二对中单击 按钮 - 在第二对之后得到副本等等。

最佳答案

您可以使用距离最近的表格元素的 next() 来查找您需要的 div。试试这个:

this.$productEdit.on('click', '.btn-copy-link', function(){
    var $cTable = $(this).closest('.table-product'),
        $div = $cTable.next('div.collapsed'),
        $ele = $cTable.clone(true);

    $ele.find('td:first').empty();
    $ele.find('.product-link-title').val($lName.val() + ' Копия');
    $ele.find('.product-link-id').val('');

    $div.after($ele); // insert table clone after previous div
    $ele.after($div.clone(true)); // append cloned div after new table clone
});

关于javascript - 使用 jQuery 在单击时复制特定结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40380571/

相关文章:

html - 我似乎无法在 html5 canvas 上画线

php - 如何在 mysqli 语句中应用正则表达式

javascript - Puppeteer - 从具有特定类名的 div 中检索链接

javascript - 我怎样才能在 vuejs 或任何其他解决方案上解决这个数组问题?

javascript - 随机数组或类似的东西

javascript - 从服务器实时更新图表

javascript - Eclipse - 撤消 "Convert to JavaScript Project..."

javascript - 检查窗口是否打开,如果没有则调用另一个 javascript 函数

javascript - 具有数据属性的 Div 元素获取具有相同数据属性 div 的单独索引

python - 如何更改 mako 替换定界符?