【问题标题】:automatically change numbering on deleting a row删除行时自动更改编号
【发布时间】:2014-05-21 09:09:12
【问题描述】:

我希望在单击按钮后删除选中复选框的表格行。我尝试了以下方法:

$(document).ready(function() {
    $('table tr').each(function(i){
        $(this).children('td:eq(0)').append(i+1);

        //button click
        $('.deletebtn').click(function(){     
            $('table input[type="checkbox"]').is(':checked')==true?$('table input[type="checkbox"]').is(":checked").parent('td').parent('tr').remove():$('table input[type="checkbox"]').parent('tr').show()
        });
    });  
});

这不起作用只是因为if statement 中的.is(":checked") 如果我删除它,代码将是:

$(document).ready(function() {
    $('table tr').each(function(i){
        $(this).children('td:eq(0)').append(i+1);

        //button click
        $('.deletebtn').click(function(){     
            $('table input[type="checkbox"]').is(':checked')==true?$('table input[type="checkbox"]').parent('td').parent('tr').remove():$('table input[type="checkbox"]').parent('tr').show()
        });
    }); 
});

这段代码删除了所有行,显然是因为我没有指明选中的复选框。所以它需要$('table input[type="checkbox"]').parent('td').parent('tr') 作为所有的行。

注意:除此之外,我还希望每个复选框旁边的编号在删除行时自动更新。

我的小提琴:http://jsfiddle.net/3RZWt/1/

【问题讨论】:

  • 您在 jsfiddle 中的 prop() 方法前面添加了 2 个点
  • .is(":checked") 返回一个布尔值,你不能用 jQuery 方法链接它。请改用filter()。要更新行号,您应该改用 CSS,例如:stackoverflow.com/a/17012547/1414562 BTW,您发布的 jsFiddle 与您发布的代码不匹配...
  • 你要this
  • 你想要这个jsfiddle.net/aamir/3RZWt/4 吗?

标签: jquery


【解决方案1】:

我希望在单击按钮后删除选中复选框的表格行。除此之外,我还希望每个复选框旁边的编号在删除一行时自动更新。

代码

$(document).ready(function () {
    //Set Numbers to span
    function AutoNumber() {
        $('table tr').each(function (i) {
            $(this).find('span').text(i);
        });
    }
    //button slick
    $('.deletebtn').click(function () {
        $('table tr').each(function (i) {
            if($(this).find('input[type="checkbox"]').is(':checked')) {
                $(this).closest('tr').remove();
            }
        });
        //After deletion
        AutoNumber();
    });
    //Call to set initially
    AutoNumber();
});

HTML,将跨度添加到第一个单元格

<tr>
    <td>
        <input type="checkbox" /><span></span>
    </td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>

DEMO

【讨论】:

    【解决方案2】:

    对行计数器使用 CSS 并修正了一些代码:

    --DEMO--

    $(document).ready(function () {
        $('.deletebtn').click(function () {
            $('table input[type="checkbox"]').filter(':checked').closest('tr').remove();
        });
    });
    

    CSS:

    table {
        width: 100%;
        counter-reset: rowNumber;
    }
    table tr {
        counter-increment: rowNumber;
    }
    table tr td:first-child::before {
        content: counter(rowNumber);
        min-width: 1em;
        margin-right: 0.5em;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2020-07-23
      • 2010-11-01
      • 2015-06-29
      • 2020-04-01
      • 1970-01-01
      相关资源
      最近更新 更多