簡體   English   中英

jQuery-無法刪除表行

[英]JQuery - can't delete table row

我不知道這段代碼有什么錯誤。 我已經正確檢測到父母了。 但是不起作用。

這是HTML代碼

<table>

    <tbody class="tbody">
        <tr id="row_1">
            <td>
                <input type="text" id="row_1_jumlah_1" name="row_1_jumlah_1" value="1" readonly="readonly" class="form-control" />
            </td>
            <td></td>
        </tr>
        <input type="button" class="btn green" value="Tambah Satuan" id="add_row" style="margin-bottom: 10px; margin-left:10px;" />
    </tbody>

</table>

這是js代碼

$("#add_row").click(function () {
    var last_index_tr = $(".tbody tr").length;
    var new_index_tr = $(".tbody tr").length + 1;
    var row = $("<tr id='row_" + new_index_tr + "'>");
    var input = $("<td>     <input  class='form-control' type='text' id='row_" + new_index_tr + "_jumlah_1' name='row_" + new_index_tr + "_jumlah_1' value='1'  readonly='readonly' /> </td>");
    var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr + "_delete' class='delete' value='delete' /> </td>");

    action_delete.click(function () {
        var parent_1 = action_delete.parent();

        var get_tr_parent_id = $(parent_1).attr('id');
        //document.write(get_tr_parent_id); 
        $("#".get_tr_parent_id).remove();
    });


    row.append(input);
    row.append(action_delete);
    row.append("</tr>");
    $(".tbody").append(row);
});

我想用刪除按鈕或action_delete刪除表內的tr(請參閱js代碼)。 我有一個完美的父母。 但是我仍然無法刪除tr。

嘗試此操作,您可以使用.on掛鈎運行時正在創建的delete buttonclick handler 盡管您的鈎子正在工作,但是使用.on是處理dynamically創建的elements一種好習慣。 順便說一下,您必須將#+ Not與連接. 那就是您的代碼的問題,請參見此處的代碼。

var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr   +"_delete' class='delete' value='delete' /> </td>"); 

$(document).on('click',"#row_" + new_index_tr +"_delete",function(){
       $(this).closest('tr').remove();
});

DEMO


編輯:

嘗試以下代碼,這對於整個刪除按鈕通常僅一次注冊到click事件。

$("#add_row").click(function () {
    var last_index_tr = $(".tbody tr").length;
    var new_index_tr = $(".tbody tr").length + 1;
    var row = $("<tr id='row_" + new_index_tr + "'>");
    var input = $("<td>     <input  class='form-control' type='text' id='row_" + new_index_tr + "_jumlah_1' name='row_" + new_index_tr + "_jumlah_1' value='1'  readonly='readonly' /> </td>");
    var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr + "_delete' class='delete' value='delete' /> </td>");  

    row.append(input);
    row.append(action_delete);
    row.append("</tr>");
    $(".tbody").append(row);
});

$(document).on('click', "input[type='button'][id$='delete']",function(){
       $(this).closest('tr').remove();
});

演示-我

您的刪除方法不正確。 它應該是:

$("#" + get_tr_parent_id).remove(); 

當前它返回的是undefined,而不是連接兩個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM