简体   繁体   中英

Deleting a specific row in a table

I'm trying to delete a specific row from a table using javascript. The way I'm trying to do it now, is by retrieving the ID of the current row by clicking a button (the delete button) and then deleting the row. The problem is that I'm not retrieving the current row ID in the table. If someone could help me retrieve the the ID of the current row when the user clicks the delete button, I think I can solve the rest myself. Thanks

/*The Javascript*/
function delete_row() {     
        alert('id goes here');
        //getElementById('row').innerHTML ='hello';
        //id.deleteRow();
        //var table = document.getElementByTagName('items_table');
        //var row = table.rows[index];
                //document.getElementByTagName('items_table').deleteRow(0);
}

/*The HTML of the Table*/
<table id="items_table">
    <tr id="row_1">
        <td>
            <input type="text" value="item1"/>
        </td>
        <td>
            <button onclick="delete_row();">X</button>
        </td>
    </tr>
/*   Five rows in this table...  */
    <tr id="row_5">
        <td>
            <input type="text" value="item5"/>
        </td>
        <td>
            <button onclick="delete_row();">X</button>
        </td>
    </tr>
</table>

You could just ascend the tree until you find a row:

function delete_row(btn) {
    var tr = btn;
    while(tr && tr.nodeName != "TR") tr = tr.parentNode;
    if( !tr) throw new Error("Failed to find the row, was the function called correctly?");
    tr.parentNode.removeChild(tr); // delete it
}

And:

<button onClick="delete_row(this);">X</button>

The this is important, as it provides a reference to the button that was clicked, so we can find the row it is in.

Check this code. It has been verified and will do your job perfectly. :)

<script>

function delete_row(me) {     
alert(me.parentNode.parentNode.id);
}
</script>

<table id="items_table">
    <tr id="row_1">
        <td>
            <input type="text" value="item1"/>
        </td>
        <td>
            <button onclick="delete_row(this);">X</button>
        </td>
    </tr>

    <tr id="row_5">
        <td>
            <input type="text" value="item5"/>
        </td>
        <td>
            <button onclick="delete_row(this);">X</button>
        </td>
    </tr>
</table>

Can't you just change <button onclick="delete_row();">X</button> to <button onclick="delete_row('row_5');">X</button> , in each row, respectively?

Your handler would look like:

function delete_row(theID) {     
        alert(theID);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM