删除元素的父行

时间:2013-07-25 10:51:54

标签: javascript jquery html-table

我在单元格中有一个带按钮的表,如下所示:

<table>
    <tr>
        <td>information</td>
        <td>
            <button onclick="function(id, this)">Text</button>
        </td>
    </tr>
</table>

按下按钮时调用的函数会执行一些ajax操作,如果成功,则应从DOM中删除按钮所在的整行。 (这是一个删除功能;)

但是,我似乎无法让jQuery删除正确的行。 我已经使用了$('#id').parent().parent().remove();,因为我认为它会去:按钮 - &gt;细胞 - &gt;行,但它只是删除表的第一行?!哪里输了? :(

4 个答案:

答案 0 :(得分:10)

http://jsfiddle.net/ZnX5J/

<table>
    <tr>
        <td>information</td>
        <td>
            <button onclick="removeRow(this)">Text</button>
        </td>
    </tr>
    <tr>
        <td>blah</td>
        <td>
            <button onclick="removeRow(this)">Text</button>
        </td>
    </tr>
</table>

的JavaScript

removeRow = function(el) {
    $(el).parents("tr").remove()       
}

答案 1 :(得分:4)

.closest()可以轻松完成 -

$(this).closest('tr').remove();

您可以删除内联onClick并像这样处理点击 -

$('button').on('click',function(){
   $(this).closest('tr').remove();
});

演示------> http://jsfiddle.net/2nJYe/

答案 2 :(得分:1)

工作演示http://jsfiddle.net/cse_tushar/6mMkM/

$('.b1').click(function () {
    $(this).parent().parent().remove();
});

答案 3 :(得分:0)

你做得对,但没有身份证,如果你这样做,它会像你期望的那样工作,

$(this).parent().parent().remove();

但在这种情况下建议使用.closest()。

$(this).closest("tr").remove();