jQuery:根据类删除行

时间:2012-10-18 16:37:04

标签: jquery jquery-selectors

我遇到了jQuery的问题,并根据他们的类删除了一些元素。见http://jsfiddle.net/JBKp4/1/

当在itemRow中单击删除链接时,该项目的optionRow和commentRow应该被删除。但我不能确定行的类别。

我希望有人可以帮助我。谢谢!

6 个答案:

答案 0 :(得分:11)

您的代码可以更简单:

$('body').on('click', '.delete', function() {
    var $tr = $(this).closest('tr');
    if ($tr.attr('class') == 'itemRow') {
        $tr.nextUntil('tr[class=itemRow]').andSelf().remove();
    }
    else {
        $tr.remove();
    }
});

看到它在这里工作:http://jsfiddle.net/RASG/MeaRQ/

答案 1 :(得分:6)

你可以通过选择器

来做到这一点
$(".className").remove();

<tr class"itemRow">中的拼写错误应为<tr class="itemRow">

答案 2 :(得分:2)

正如其他人所指出的那样,修复您的class属性。

你的JavaScript也可以变得更清晰:

$(document).ready(function() {
    $('body').on('click', '.itemRow .delete', function() {
        $(this).parents('tr').nextUntil('.itemRow').andSelf().remove();
    });

    $('body').on('click', '.optionRow .delete', function() {
        $(this).parents('tr').remove();
    });
});​

演示:http://jsfiddle.net/JBKp4/35/

答案 3 :(得分:1)

嵌套你的行。不是在表格中为每个项目创建新行,而是按层次结构嵌套:

<table class="items">
    <tr class="item">
        <table class="options">
            <tr class="option">
                <table class="comments">
                    <tr class="comment">
                    </tr>
                </table>
            </tr>
        </table>
    </tr>
</table>

老实说,我建议不要使用表格。看起来您的内容不会是表格数据,因此表格对布局没有意义。改为使用Div。

答案 4 :(得分:1)

解决其他人注意到的=问题。还有更多的东西。

您需要一种方法将项目与其选项相关联。我建议你只更新html:

<tr class="itemRow" id="item1">
...
<tr class="optionRow item1">
...

请注意,optionRow应该将其所属项目的ID作为类。这样,当您删除项目行时,您可以执行以下操作:

$("." + this.id).remove();

请参阅:http://jsfiddle.net/JBKp4/11/

如果你不想这样做(或因某些原因不能),那就更复杂了。基本上你必须继续获得itemRow TR的.next(),直到它遇到另一个.itemRow或者没有下一个TR。

答案 5 :(得分:0)

首先,你的标记被误导了。您在=元素的类属性中缺少tr。干净的标记使得JS方面的事情变得更容易管理。我建议你修改你的标记,甚至将它重构为更具语义性(将数据组合成使用<dl><ul>等元素有意义的结构。

更好的html =减少工作量。

其次,您绑定了正文 .delete元素。这在jQuery必须要做的事件监视方面有很多开销。对于您想要实现的功能类型,这是不必要的。仅绑定到要跟踪事件的元素,使用回调来处理相关案例。

最后,绝对没有任何内容可以将您的<tr>元素链接在一起,这表明这些行与您尝试删除的行相关。因此,您的脚本只删除了一行。您可以使用data-attributes和其他元素属性将目标元素链接在一起。我更新了你的小提琴,告诉你我的意思。 Your Updated Fiddle...

这是修订后的jQuery脚本:

jQuery( function(){
    $('.delete').click( function(){
        var obj = $( this ); // your delete link
        var table = obj.closest('table'); // the containing table
        var trgroup = obj.attr('data-group'); // a data-attribute that links your other elements together

        if( trgroup ) // If the attribute is available continue...
        {
            console.log( table.find('tr[rel="' + trgroup + '"]') );
            // Find all related element and remove them.
            table.find('tr[rel="' + trgroup + '"]').empty().remove();
        }

        // Remove the table row of the executing link and it's children.
        obj.closest('.itemRow').empty().remove();
    });
} );

我可能会因为使用empty()。remove()而不仅仅是.remove()而感到有点尴尬,但这是我自己的偏好。