开发者

How can I compare a live element to one stored in data?

I have a series of divs:

<div class="some_class active">Some Content</div>
<div class="some_class">Different Content</div>
<div class="some_class">More Different Content</div>

(active class changes dynamically)

Each has been assigned to d开发者_运维知识库ata of an image element thusly:

$("div.some_class").each(function(){
        current = $(this);

        $('div#images').append('<img class="link new" src="/style/images/image.png" />');
        $(".link.new").removeClass('new').data('project', current);
    });

I want to use this function to compare the active element to those stored in data:

function live_test(){

        active = $("div.some_class.active");
        $("#images img.link").each(function(){

            if ($(this).data('project') == active){
                $(this).addClass("active");
            }
        });
    }

The intention being to add a class of active to the image that holds the same div.some_element as the one that has the active class, but this function returns false all the time, never finding a match. I am pretty sure I am missing a fundamental here, but what? And is there any other way to do it?


You are comparing 2 jquery objects. These objects will never be the same. What you want to compare are the elements within the jquery objects. Assuming both can only ever have one element, do this:

if ($(this).data('project')[0] == active[0]){

Edit:
While the above should answer your question, why not do the reverse of what you're doing. Rather than store the element on the image, store the image (or id of the image) on the element. Then you can easily grab the image related to the given element. You want to avoid looping when possible.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜