【问题标题】:Can't delete current row of jQuery DataTable using local button无法使用本地按钮删除 jQuery DataTable 的当前行
【发布时间】:2018-09-05 14:25:22
【问题描述】:

我有一个 jQuery 数据表,我动态添加行。每行都有一个单元格,其中有一个删除按钮。我的问题是我无法使用按钮删除行,甚至无法定位当前行。

这是我的数据表代码:

var tab_presta = $("#tableau_presta").DataTable({
    "searching": false,
    "paging":   false,
    "ordering": false,
    "info":     false,
    responsive: true,
    "language": {
        "emptyTable": "No product added to the contract for the moment."
      }
});

这是我如何在每一行上创建按钮(在提交事件中):

form2.on('submit', function (event) {

tab_presta.row.add( 
    [            
        '<center><button type="button" id="btn_supp' + (++idCount) + '" onclick="alert(this.parentNode)" class="btn btn-xs btn-block btn-danger confirmation">Delete</button></center>'
    ] 
)
.draw( false );

// here I dynamically add an id to each button based on a variable
$('.btn btn-xs btn-block btn-danger confirmation').each(function() {
        $(this).attr('id', 'suppr' + idCount);
        idCount++;
    });
});

这是我在单击每个按钮时删除的代码:

for (j = 0; j <= btn_count; j++) {
    $("#tableau_presta").on("click", btn_supp[j], function(){
        //tab_presta.row($(this).parents('tr')).remove().draw(false);
        var row = $(this).closest("tr");
        console.log(row);
    });
}

如您所见,我评论了 remove() 部分,因为它不起作用,所以我试图找到最接近 tr$(this) (button),但结果我没有在控制台中获得该行.它是空的,我不明白为什么,因为按钮确实存在,如果我输入onclick"alert(this.id),我可以在单击它时获取它的 id。

有什么想法吗?

【问题讨论】:

    标签: javascript jquery html css datatable


    【解决方案1】:

    您不需要在循环内绑定点击事件。相反,请使用classattribute selector。在这种情况下,选择所有具有id^btn_supp = [id^=btn_supp] 开头的元素。

    $("#tableau_presta").on("click", "[id^=btn_supp]", function() {
      $(this).closest("tr").remove();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="tableau_presta">
      <tr>
        <td>
          <button type="button" id="btn_supp1" class="btn btn-xs btn-block btn-danger confirmation">Delete</button>
        </td>
      </tr>
      <tr>
        <td>
          <button type="button" id="btn_supp2" class="btn btn-xs btn-block btn-danger confirmation">Delete</button>
        </td>
      </tr>
    </table>

    【讨论】:

    • 非常感谢@Serg,它有效!虽然我真的不明白为什么我的循环不起作用?
    • 在循环中分配事件是多余的,而且有点糟糕。然而,真正的问题可能是btn_supp[j]。看起来它至少应该是"#btn_supp"+j。你应该提供一个 CSS 选择器。
    • 我现在遇到了另一个问题:当我单击按钮时,它会按要求删除行,但是当我动态添加另一行(通过另一个表单)时,它会添加新行和行我已经删除了。我试图在“.remove()”之后添加“.draw(false)”,但它不起作用。一个想法?
    • 我不熟悉 DataTable 插件,听起来你只是从列表中生成行。删除时,您不会从数据源中删除,因此它们最终会被读取。只是猜测,这应该是一个新问题。
    • 非常感谢您的回答@Serg,我找到了其他问题的答案。你是对的,它是一个插件,所以我必须按照插件的方式来做。这是我按照官方网站建议编辑后的函数: tab_presta.on("click", "[id^=btn_supp]", function() { tab_presta.row($(this).closest("tr")) .remove().draw(); }); “tab_presta”实际上是: var tab_presta = $("#tableau_presta").DataTable({ blabla.. });再次感谢您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多