首页 > 解决方案 > jquery - 从克隆的 html 中替换一个元素

问题描述

我想实现以下两种情况:

  1. 需要在单击加号按钮时添加行。

  2. 需要用动态添加的行中的超链接替换加号按钮。

<button type="button" class="addRow" />+</button>

对于所有动态添加的行,将上面的按钮替换为下面的按钮。

<a href="javascript: void(0)" title="Click to remove">Remove</a>

我已经完成了第一个场景并坚持使用第二个场景。

HTML:

<table id="exampleTbl">  
    <tr>
        <td>1</td>
        <td>2</td>
        <td>
           <button type="button" class="addRow" />+</button>
       </td>  
    </tr>
    <tr>
        <td>3</td>
        <td>4</td>
        <td>
           <button type="button" class="addRow" />+</button>
       </td>  
    </tr>
</table>

jQuery:

$(function() {
    $('#exampleTbl').delegate('button.addRow', 'click', function() {
        var row = $(this).closest('tr'); // get the parent row of the clicked button
        var html = $(this).closest('tr').clone();
        $(html).insertAfter(row); // insert content
    });
});

标签: htmljquery

解决方案


你可以试试这个。

$(function() {
  $('#exampleTbl').delegate('button.addRow', 'click', function() {
    var row = $(this).closest('tr'); // get the parent row of the clicked button
    var html = $(this).closest('tr').clone();
    $(html).insertAfter(row); // insert content
    
    let btn = $('<a href="javascript: void(0)" title="Click to remove">Remove</a>');
    btn.click(function () {
      $(html).remove(); // Remove row on click
    })
    
    $(html).find('.addRow').replaceWith(btn);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="exampleTbl">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>
      <button type="button" class="addRow">+</button>
    </td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
    <td>
      <button type="button" class="addRow">+</button>
    </td>
  </tr>
</table>

工作 JSFiddle:https ://jsfiddle.net/j18yfwLv/1/

注意:我刚刚将按钮替换为您想要的内容,您是否希望按钮也删除该行?


推荐阅读