繁体   English   中英

通过循环删除DOM元素

[英]Delete DOM elements throught loop

我正在尝试创建一个负责删除DOM元素(将HTML表格中的一行或几行)删除的循环:

<tr class="entireLine><input type="checkbox"></tr>
<tr class="entireLine><input type="checkbox" checked></tr>
<tr class="entireLine><input type="checkbox" checked></tr>

JS

for (var i=0; i<$(".entireLine").length; i++){
        // Get the current line of the table
        var currentLine = $(".entireLine")[i];
        // Get the checkbox in the DOM element
        var checkbox = $(currentLine).find("input[type=checkbox]");
        // Check the state of the checkbox. If checked, remove the line. 
        if ( $(checkbox).is(":checked") ) {
            $(currentLine).remove();
        }
    }

仅当选择了一行时,此代码才能正常工作。 在选择的2行中,第二行不会删除,因为在第一次删除后索引(i)不好。

我的错误在哪里?

您可以通过选中的复选框找到tr

$(".entireLine").has('input[type=checkbox]:checked').remove()

在您的循环中,问题是表达式$(".entireLine").length在每次迭代中都会求值,如果在上一次迭代中删除了item,它将减少长度,但是i的值没有减少,因此会有些遗漏项目

每个使用一个jQuery:

$(".entireLine").each(function( index ) {
    if ($(this).find("input[type=checkbox]").is(":checked")) {
        $(this).remove();
    }
});

并更正您的HTML,它不是<tr class="entireLine>而是<tr class="entireLine"> (您忘记了结尾的"

颠倒您的想法-而不是遍历所有行来查找选定的项目,而是找到选定的项目然后删除其行:

$(":checkbox:selected").each(function() {
    $(this).closest("tr").remove();
});

我会做这样的事情,而不是做for循环。 这将找到所有复选框,并执行$ .each,如果选中它们,则会将其删除。 我将复选框放在其自己的var中以进行调试。

var checkboxes = $('input[type=checkbox]'); 

checkboxes.each(function(){
        var $checkbox = $(this); 
        if ( $checkbox.is(":checked") ) {
            $checkbox.remove();
        }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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