簡體   English   中英

如何在單擊相應行的按鈕時刪除表行?

[英]How to delete a table row on button click of corresponding row?

這是我的代碼:

    function deleteHostTable(src) {
        var table = src.parentNode.parentNode.parentNode;
        if(table.rows.length > 1) {             
            table.deleteRow(src.parentNode.parentNode);
        }
         }
    function addHost(src) {
         var table = src.parentNode.parentNode.parentNode;
        var newRow = table.insertRow(table.rows.length-1);

        var cell = newRow.insertCell(newRow.cells.length);

        cell.innerHTML = '<input type="hidden" name = "vtierIdH" value = "vtierId" />'

        cell = newRow.insertCell(newRow.cells.length);
        cell.innerHTML = '<img src="images/minus.gif" onclick="deleteHostTable(this);return false;"/>';

        cell = newRow.insertCell(newRow.cells.length);
        cell.className = "pagetitle";
        cell.innerHTML = '<input type = "text" value="hstst" />';
    }
</script>
<html>
<table id="host#1" index="1">
        <tr>
            <td colspan="10">
            <h2 align="left" class="pagetitle">Sub Account Hosts:</h2>
            </td>
        </tr>
        <tr>
            <input type="hidden" name="vtierIdH" value="<%=vtierId %>" />

            <td><button id="minus" onclick="deleteHostTable(this);"/></td>
            <td class="pagetitle"><input type="text" value="hstst" /></td>
        </tr>
        <tr>
            <td><button  onclick="addHost(this);"></td>
        </tr>
    </table>
</html>

現在,當我單擊與按鈕相對應的按鈕時,此代碼將刪除最上面的行,而不是與被單擊的按鈕相對應的行。 如何刪除該行中與按鈕對應的行?

只需將刪除功能更改為

function deleteHostTable(src) {
    var row = src.parentNode.parentNode;
    row.parentNode.removeChild(row);
}

它不適用於deleteRow的原因是,它希望在傳遞對象時傳遞行的索引。

您必須將“索引”傳遞給table.deleteRow函數,而不是元素。

function deleteHostTable(src) {

    var table = src.parentNode.parentNode.parentNode;
    var row = src.parentNode.parentNode;
    for(var i = table.rows.length; i--; )
    {
        if ( table.rows[i] == row )
        {
            table.deleteRow(i);
            return;
        }
    }

}

此功能應該起作用。

您還可以使用src.parentNode.parentNode.parentNode.removeChild(src.parentNode.parentNode)

暫無
暫無

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

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