jQuery .remove()在迭代变量时不起作用

时间:2015-04-01 19:13:19

标签: jquery

我似乎无法让我的jQuery代码正常工作。我正在尝试修改表行集合。这是我的代码:

//rowCollection: a number of <tr> elements without a parent element (i.e. <tr /> <tr /> <tr />....)
//currentRow: any <tr /> element that is also contained in 'rowCollection'
function removeCurrentRow(rowCollection, currentRow) {
    var filteredRowCollection;
    filteredRowCollection = rowCollection;

    filteredRowCollection.each(function () {
        if($(this).text() == currentRow.text()){
            filteredRowCollection.find($(this)).remove();
        }
    });

    return filteredRowCollection;
}

基本上,我试图从变量中删除一行(不是实际的页面html,它应该在浏览器中保持可见)。但是当我输出原始行集合和已过滤行集合的文本时,它仍然是相同的。

function highLightRedundantTimes() {
    var rowCollection = $('.ms-listviewtable:first > tbody  > tr');

    rowCollection.each(function () {

    var filteredRowCollection = removeCurrentRow(rowCollection.clone(), $(this));

    console.log("Original: " + rowCollection.text());
    console.log("This: " + $(this).text());
    console.log("Filtered: " + filteredRowCollection.text());
    console.log(" ")
});
}

有人可以帮助我吗?

编辑:

我的rowCollection看起来像这样:

<tr><td>text</td><td>text</td><td>text</td><td>text</td></tr>
<tr><td>value</td><td>value</td><td>value</td><td>value</td></tr>
<tr><td>text</td><td>text</td><td>text</td><td>text</td></tr>

在这种情况下,当使用第一个/第三个<tr>作为“currentRow”进行迭代时,它将从“filteredRowCollection”中删除,并且仅保留第三个/第一个和第二个<tr>

1 个答案:

答案 0 :(得分:2)

如果我理解您的代码,我认为您错误地使用了$this

filteredRowCollection.each(function () {
    if($(this).text() == currentRow.text()){
        filteredRowCollection.find($(this)).remove();
    }
});

尝试,如下所示。

$this,引用当前范围,因此我认为$this = filteredRowCollection

filteredRowCollection.each(function () {
    if($(this).text() == currentRow.text()){
         $(this).find(currentRow.text).remove();
    }
});

此外,您正在使用每个循环,因此可能不需要查找。

更新

$(this)代表集合,因此使用$(this).children().remove()会将您带入集合项目并从行中删除该项目。