javascript - 使用 filter() 的正确方法是什么?

标签 javascript jquery

我正在使用 filter(),我想知道这种方法是否正确?

使用过滤器,它寻找匹配的 noteid 并删除图像。

$.post("monitoring_ajax.php", {
    action: "removeNote",
    noteid: noteid
}, function(data) {

    $(".noteicon").filter(function(){  
        if ($(this).data('note-id') == noteid) {
            $('img', this).remove();
        }
    });

});

最佳答案

来自 jQuery 文档:

.filter():

Reduce the set of matched elements to those that match the selector or pass the function's test.

因此,我建议使用 .filter() 方法来减少选定的元素,然后然后在匹配的元素上链接其他方法元素。

在您的情况下,您可以使用:

$(".noteicon").filter(function(){  
    return $(this).data('note-id') == noteid; // Returns element if true
}).find('img').remove();

如果您不修改代码,那么 .each() 可能是 .filter() 的更好替代品,因为您只是迭代代码:

$(".noteicon").each(function(){  
    if ($(this).data('note-id') == noteid) {
        $('img', this).remove();
    }
});

关于javascript - 使用 filter() 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31327262/

相关文章:

jquery - 谁能帮我简化 bootstrap 选项卡 Pane 的 jQuery 代码

jquery - 在 WordPress 中添加指向特定页面的链接

javascript - Angular 中的 HTML 片段在 View 中部分缺失

javascript - 如何在jquery中以编程方式选择可选择的项目?

javascript - 视频JS : Object doesn't support property or method 'querySelector'

jquery - 使用两个变量创建 jQuery 对象

javascript - 如何像Twitter一样显示不改变url的输入表单?

javascript - 如何在 pm2 中使用 Grunt/Gulp?

javascript - Globalize.js 不只在德国文化中格式化日期

javascript - jQuery 不会在 select 标签内添加附加选项标签