tags:

views:

106

answers:

3

I'm trying to write a loop to iterate over each anchor in an unordered list and perform an action on an image inside the anchor. The markup looks like this:

 <ul>
    <li><a href="#"><img src="image.png" /></a></li>
    <li><a href="#"><img src="image.png" /></a></li>
    <li><a href="#"><img src="image.png" /></a></li>
</ul>

A click event on any one of the anchors should trigger the loop. I have the following JS so far:

$("a").click(function(){
    $("a").each(function(){
        if (THIS IS THE CLICKED ON ANCHOR == TRUE) {
            // SKIP THIS ITEM
        }
        else {
            $("img",this).actions();
        };
    });
});

I think I just need the part that skips the item if it is the clicked on anchor, but I'm not apposed to a different approach.

I'm using jQuery 1.3.2.

Thanks!

+1  A: 

You could try:

$("a").click(function(){
    var clickedItem = this;
    $("a").each(function(){
        if (this == clickedItem) {
            // SKIP THIS ITEM
        }
        else {
            $("img",this).actions();
        };
    });
});
Sinan Taifour
Thanks! I just realized that right after I asked. You get the credit for posting the answer before me.
Ben
A: 

Looks like I figured it out, I just needed to save this from the click event:

$("a").click(function(){
    var clickedOnAnchor = this;
    $("a").each(function(){
        if (clickedOnAnchor == this) {
            // SKIP THIS ITEM
        }
        else {
            $("img",this).actions();
        };
    });
})
Ben
Watch out! If you declare a variable without the `var` keyword (like `clickedOnAnchor` in your case) it becomes a **global** variable. You probably don't want that.
Sinan Taifour
Ben -- I think this is more complicated than it needs to be. See my answer.
tvanfosson
+6  A: 

I think there's an easier way:

$("a").click(function() {
   $("a").not(this).find('img').actions();
});
tvanfosson
You're right this is a much cleaner implementation. Thank you.
Ben