簡體   English   中英

使用filter()的正確方法是什么?

[英]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()

將匹配元素的集合減少到與選擇器匹配或通過功能測試的元素。

因此,我建議使用.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM