Hello,

this is one of the possible generic ways to do it using closures:

        for (var i=0;i<whatever;i++) {
                (function() {
                        var my_i = i;
                        $("#something").click(function(){ do_it(my_i)});
                })();
        }

depending on your real code, it can surely be written in better ways.

On Oct 29, 5:29 pm, The alMIGHTY N <natle...@yahoo.com> wrote:
> Example page:http://jqueryfun.nathanielklee.com/eventFirefox.html
>
> Following one example provided in an official jQuery tutorial (located
> athttp://docs.jquery.com/Tutorials:How_jQuery_Works), I can pass
> "event" into a function I define directly in the click assignment
> handler.
>
> e.g. $("#something").click(function(event) { event.preventDefault
> (); });
>
> However, if this is put into a for loop and modified to include a
> statement that requires a value of i from the for loop iteration, it
> won't work because when the handler is fired, it only knows the last
> iterative value of i.
>
> I get around that by instead making a call to a function that returns
> a function that executes the statements I want.
>
> e.g. $("#something").click(doSomething(i)); function doSomething(i)
> { return function() { alert(i) }; }
>
> So far, so good.
>
> The problem I run into is that I need to prevent the default behavior
> with event.preventDefault(). Browsers won't recognize if I pass
> "event" into the function even though the aforementioned tutorial
> indicates that one can indeed pass "event" into a function. How can I
> get around this problem?
>
> I realize that there are other ways I could do the same thing, such as
> applying a class to the links in question and referencing the event
> target (example below), but I'm interested in figuring out why the
> method I described above doesn't work and whether there's a way to get
> it to work.
>
> e.g. $("#something").click(doSomething); function doSomething(event)
> { alert($(event.target).attr("anAttribute")); }
>
> Thanks!

Reply via email to