开发者

jQuery $get() - compare loaded data with each()

开发者 https://www.devze.com 2023-01-20 22:03 出处:网络
I have two lists .album and .favorites First I was using this each() loop to compare the .album items against the .favorites

I have two lists .album and .favorites

First I was using this each() loop to compare the .album items against the .favorites

When there is a favorite copy in the .album list I append a favorite icon.

$(".album li").each(function(index) {
    var itemSrc = $(this).find("img").attr("src");
    if ( $(".favorites li img[src*='" + itemSrc + "']").length > 0 ) {
        $(this).append('<span class="favorite"><\/span>');
    }
});

Now I switched to an approach where I load the favorites in later, so I need to use $get() to compare the loaded data with my .album items

$.get("ajax-load-favorites.php", {}, function(data) {
    // console.log(data);
    $(".album li").each(function(index) {
        var itemSrc = $(this).find("img").attr("src");
        /* compare with data here */
    });
});

ajax-load-favorites.php returns this:

<li><img src="http://mysite.com/album/tn/006.jpg" /></li>
<li><img src="http://mysite.com/album/tn/003.jpg" /></li>
<li><img src="http://mysite.com/album/tn/0开发者_StackOverflow10.jpg" /></li>


A simple string search would solve your problem:

$.get("ajax-load-favorites.php", {}, function(data) {
    // console.log(data);
    $(".album li").each(function(index) {
        var itemSrc = $(this).find("img").attr("src");
        if (data.indexOf(itemSrc) != -1) {
            $(this).append('<span class="favorite"><\/span>');
        }
    });
});


$.get("ajax-load-favorites.php", {}, function(data) {
    // console.log(data);
    $("li", data).each(function(index) {
        var itemSrc = $(this).find("img").attr("src");
        if ( $(".favorites li img[src*='" + itemSrc + "']").length > 0 ) {
           $(this).append('<span class="favorite"><\/span>');
        }
    });
});

It's basically the same, just modify the selector to search in your ajax-loaded data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号