我正在使用 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 文档:
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/