Sqoo
Sqoo

Reputation: 5243

Binding a jQuery click event to each element within a foreach loop

I am building a plugin which matches an element, finds a link within it and makes the parent element go to that location upon a click.

I have a loop in the main body:

    return this.each(function(options) 
{

    $to_link = $(this); //matched object
    link_href = $('a', $to_link).attr('href'); //link location
    $($to_link,$parent)
        .click(function(){alert(link_href); window.location = link_href; return false;})
        .attr('title','Jump to ' + link_href);
})

which I am running it against this HTML

<div id="a"><h2><a href="/products/">Products</a></h2><p>blah blah</p></div>
<div id="b"><h2><a href="/thinking/">Thinking</a></h2><p>liuhads</p></div>

The problem I have is that the click function always results in jumping to the value of the last matched div's link although the title of the element has the correct value.

To clarify, behavious should be:

instead, what happens is:

ie div#a ends up with the wrong behaviour. Im guessing this is some kind of scope issue but for the life of me I cannot see it, help!

Upvotes: 2

Views: 6605

Answers (2)

Sqoo
Sqoo

Reputation: 5243

There is a fuller answer to the general case here

http://www.foliotek.com/devblog/keep-variable-state-between-event-binding-and-execution/

answer #2 is to use a closure to force a new level of scope :)

Upvotes: 4

ironfroggy
ironfroggy

Reputation: 8109

You are forgetting the var in your assignments, so you're sharing one global variable and getting them mixed up.

$to_link = $(this); //matched object
link_href = $('a', $to_link).attr('href'); //link location

should be

var $to_link = $(this); //matched object
var link_href = $('a', $to_link).attr('href'); //link location

Otherwise, link_href will retain the last value, and that is the value the click handler will see when its called.

Upvotes: 4

Related Questions