【问题标题】:Removing dynamically created lines in table删除表中动态创建的行
【发布时间】:2015-06-26 03:13:43
【问题描述】:

我有一个表格,我在其中动态添加新行。 添加一行后,它看起来像这样:

<table>
<tbody id="list">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
  <tr class="new1">                           //
    <td class="new1">D</td>                   //
    <td class="new1">E</td>                   //  These lines
    <td class="new1">                         //  are dynamic
      <a href="#confirm" class="new1">X</a>   //
    </td>                                     //
  </tr>                                       //
</body>
</table>

我希望能够通过单击最后一列中的 X 符号来单独删除新行,这会将我重定向到对话框以确认这一点。 对话框很简单 - 两个按钮:是/否。

我的想法是获取单击元素的类,将其保存为变量,然后在单击“是”按钮时使用它来删除具有该特定类的所有元素。

我制作的脚本是这样的:

// For saving class of clicked link in list
var delId;
$(document).on("click", "#list a", function(){
  delId= $(this).attr("class");
});

// Then I try to remove elements by class
$("#idOfYesButton").click(function(){
    $("."+delId).remove();
});

但它不知何故什么也没做,我不知道为什么,所以如果你能告诉我哪里做错了,我将不胜感激。

【问题讨论】:

  • &lt;/body&gt; 应该是 &lt;/tbody&gt;。这是复制错误还是在真实代码中?
  • 在这里工作:jsfiddle.net/barmar/r9pbj2bd/3。您的 #idOfYesButton 处理程序在 $(document).ready() 内吗?

标签: jquery dynamic html-table


【解决方案1】:

试试这样的:fiddle

<table>
    <tr class="new1">
        <td class="new1">D</td>
        <td class="new1">E</td>
        <td class="new1"> <a href="#" class="remove">X</a> 
        </td>
    </tr>
    <tr class="new1">
        <td class="new1">D</td>
        <td class="new1">E</td>
        <td class="new1"> <a href="#" class="remove">X</a> 
        </td>
    </tr>
    <tr class="new1">
        <td class="new1">D</td>
        <td class="new1">E</td>
        <td class="new1"> <a href="#" class="remove">X</a> 
        </td>
    </tr>
</table>

jQuery

$(".remove").click(function () {
    if (confirm("sure you want to delete?") === true) {
    $(this).closest('tr').remove();
    }
    else return;
});

【讨论】:

    【解决方案2】:

    试试这个脚本

    $(document).on("click", "#list tr td a", function(){
      if(confirm($(this).attr("class")))
            $("."+$(this).attr("class")).remove();
    });
    

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      相关资源
      最近更新 更多