我正在使用filter(),我想知道这是正确的方法吗?
使用过滤器,它寻找匹配noteid并删除图像.
$.post("monitoring_ajax.php", {
action: "removeNote",
noteid: noteid
}, function(data) {
$(".noteicon").filter(function(){
if ($(this).data('note-id') == noteid) {
$('img', this).remove();
}
});
});
Run Code Online (Sandbox Code Playgroud)
来自jQuery文档:
将匹配元素集减少到与选择器匹配的元素或传递函数的测试.
因此,我建议使用该.filter()方法来减少所选元素,然后在匹配元素上链接其他方法.
在您的情况下,您可以使用:
$(".noteicon").filter(function(){
return $(this).data('note-id') == noteid; // Returns element if true
}).find('img').remove();
Run Code Online (Sandbox Code Playgroud)
如果你不修改你的代码,那么.each()可能是一个更好的替代,.filter()因为你只是迭代代码:
$(".noteicon").each(function(){
if ($(this).data('note-id') == noteid) {
$('img', this).remove();
}
});
Run Code Online (Sandbox Code Playgroud)