[英]What is the correct approach to use filter()?
我正在使用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()
方法來減少所選元素, 然后在匹配的元素上鏈接其他方法。
就您而言,您可以使用:
$(".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();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.