Jquery从最近的表中删除所有行
我有多个html表,每个表的行数可变 每行都有一个下拉列表元素。当该元素更改时,我希望删除该表中的所有行 我试过:Jquery从最近的表中删除所有行,jquery,Jquery,我有多个html表,每个表的行数可变 每行都有一个下拉列表元素。当该元素更改时,我希望删除该表中的所有行 我试过: $(document).on('change', '.classofmydropdownlist', function () { var self = $(this); var thisTable = self.closest('table') var rows = thisTable.children('tbody').children('tr');
$(document).on('change', '.classofmydropdownlist', function () {
var self = $(this);
var thisTable = self.closest('table')
var rows = thisTable.children('tbody').children('tr');
rows.each(function (element) {
$(element).remove();
});
$.get('/Fetchmoreitems', { 'type': self.val() }, function (html) {
thisTable.append(html);
});
}
但是行不会删除(尽管$.get successfully append调用了新项)问题在于
each()
处理程序的第一个参数是匹配集中元素的索引,而不是对元素本身的引用-这是第二个参数:
rows.each(function (i, element) { // note 'i' here
$(element).remove(); // or just $(this).remove() if you don't want to use any params
});
还请注意,使用empty()
,可以简化逻辑:
问题是因为
each()
处理程序的第一个参数是匹配集中元素的索引,而不是对元素本身的引用-这是第二个参数:
rows.each(function (i, element) { // note 'i' here
$(element).remove(); // or just $(this).remove() if you don't want to use any params
});
还请注意,使用empty()
,可以简化逻辑:
请包括html以及在
的回调中传递的第一个参数。每个(函数(idx,元素){…})
是当前元素的索引:thisTable.children('tbody')。children('tr')。remove()
就足够了,不需要each()
。同样对于引用对象,请使用this
,$(this.remove()
请包括html以及回调中传递的第一个参数。each(function(idx,element){…})
是当前元素的索引:thisTable.children('tbody')。children('tr')。remove()
就足够了,不需要each()
。也可以使用this
,$(this.remove()
感谢您,这是一个简单的解决方案,非常感谢!该元素也绑定到该,因此您可以直接使用该元素而忽略参数。@RobbieMills没问题,很高兴为您提供帮助谢谢,这是一个简单的解决方案,非常感谢!该元素还绑定到this
,因此您可以直接使用该元素而忽略参数。@RobbieMills没问题,很乐意提供帮助。@RobbieMills