Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to pass an element to a function and then match that specific element while traversing parent. The catch (for someone clueless like me) is that this element doesn't have an id. In the following example, I want every element to turn pink except the one clicked on that should turn yellow

function colorize(element) {
    element.parent().find('span').each(function() {
        if ($(this)===element) { // the problem is this is always false
            $(this).css('background','yellow');
        } else {
            $(this).css('background','pink');
        }
    });
}
$('span').click(function() {
    colorize($(this));
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
309 views
Welcome To Ask or Share your Answers For Others

1 Answer

Comparing JQuery objects will never return true, because each JQuery object is a a new object, even if their selectors are equal.

To compare elements, you have to check whether the DOM elements are equal:

this === element.get(0);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...