javascript - 使用 jQuery 删除 HTML 表格行

标签 javascript php jquery html html-table

我有一个 HTML 表,可以通过单击按钮动态添加行(也可以使用 jQuery 完成)。我现在想要的是,我需要在每行旁边有一个按钮。按下它会删除该特定行。

表格如下。

<tr class="item-row">
         <td class="item-name">
          <div class="delete-wpr"><textarea></textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>

           <td><input type="text" class="slno"/></td>           

          <td><input type="text" class="cost"/></td>
          <td><input type="text" class="qty"/></td>
          <td><span class="price"></span></td>
      </tr>  

添加更多行的Jquery如下。

 $("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><input type="text" class="slno"/><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td><input type="text" class="slno"/></td><td><input type="text" class="cost"/></td><td><input type="text" class="qty"/></td><td><span class="price"></span></td></tr> ');

我正在使用的功能是这个。但它不起作用。

$(".delete").on('click',function(){
$(this).parents('.item-row').remove();
update_total();
if ($(".delete").length < 2) $(".delete").hide();
  });

那么我该怎么做呢?

最佳答案

由于行是动态的,您需要一个委托(delegate)事件处理程序,附加到元素的不变祖先。如果没有更接近/方便的情况,document 是最好的默认值:

$(document).on('click', ".delete", function(){
    $(this).closest('.item-row').remove();
    update_total();
    if ($(".delete").length < 2) $(".delete").hide();
});

在您的示例中,table 元素将是一个很好的目标。

例如

$('#items').on('click', ".delete", function(){
    $(this).closest('.item-row').remove();
    update_total();
    if ($(".delete").length < 2) $(".delete").hide();
});

委托(delegate)事件的工作方式是在事件发生时应用 jQuery 选择器,而不是在事件注册时应用。这意味着它们可以稍后存在。

关于javascript - 使用 jQuery 删除 HTML 表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881025/

相关文章:

javascript - 无法将照片或图像链接到 CodePen

javascript - Angular.js对已过滤的数据进行分页并显示总项目,而无需在 View / Controller 中重复代码

javascript - Drupal - 轻松将自定义代码转换为 drupal 模块?

javascript - 具有 100% 高度元素的重叠 masonry

javascript - 函数 remove() 后的剩余 ID 降档

javascript - 悬停时 HTML/JavaScript 展开按钮/div

php - 在 OOP 插件中使用 WordPress admin_notices

php - jQuery + AJAX 检索输入提交类型发送的数据

javascript - 如何将值从 iframe 传递给父级?

javascript - 使用 jQuery 使用值和类根据复选框过滤结果