Christopher Jordan schrieb:
> Hi folks,
>
> I've got a function that builds several elements on a page with a
> certain class. I've successfully used jQuery to add mouseover and
> mouseout events to all the elements with that certain class, and it
> works beautifully. I couldn't be happier. :0)
>
> So, now I need to add a click event to each of those elements. The
> trouble is, that not each of those click events will be exactly the
> same. Each will call the same function but with slightly different
> arguments (one constant and one variable). After playing with a couple
> of ideas on how to use jQuery to accomplish this, I ended up with the
> following:
>
> ... inside a JS for loop with a counter 'i' ...
>
>
> $("##MyContainerID").append("<span id=\"id_" + i + "\"
> class=\"MyClass\" value=\"" + i + "\">" + i + "</span>");
> $("##id_" + i).click(
> function(){
> foo(i,ConstantArgument);
> }
> );
>
> ... end loop ...
>
> The loop creates each of these elements on the page and I was hoping it
> would then assign a click event to each element (made unique with the
> id), and this seemed to work. However when I click on each of the
> elements in turn I can see that they are each calling the function (foo)
> with the same arguments (30,40). While 40 is the constant argument and
> is correct, the other argument was supposed to range from 1 - 29 (the
> number of elements in this particular list).
>
> I'm a bit confused I thought this should work. Can anyone shed any light
> on what I may be doing wrong? Is there a different approach i need to
> take? Is there a better jQueryie-type way to accomplish this task that
> will make life easier?
>
> Thanks,
> Chris
Hey Chris,
you would have to use a closure for that to capture the value of i in
the scope of each click event handler. But you can simply use jQuery's
each(), that does it right away for you:
So try this:
$('.certainClass').mouseover(...).mouseout(...).each(function(i) {
$('<span>' + i + '</span>')
.appendTo('#MyContainerID')
.click(function () {
foo(i,ConstantArgument);
});
});
Does that work?
-- Klaus
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/