[英]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)不好。
我的错误在哪里?
每个使用一个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.