Joe L wrote:
Hi, I added the click event to a few <a> and they work perfectly fine,
but when I try to do it with a FOR loop, it doesn't work anymore, does
anyone has any idea about it?

Thank you.

/* works well */
        $("a#1-a").click(function(){toggleTab(0);});
        $("a#2-a").click(function(){toggleTab(1);});
        $("a#3-a").click(function(){toggleTab(2);});


/* doesn't work */
        var k=0;

        for (k=0;k<totalNumberTabs;k++)
        {
                $("a#" + (k+1) + "-a").click(function(){
                        toggleTab(k);
                });
        }

This is a classic so to say. By the time of the click handler gets called k has the value it had at the time of the last loop.

You would need to capture the value in a closure.

But: You can do that more easily with jQuery. First of all, an id in HTML must not start with a number:
http://www.w3.org/TR/html401/types.html#type-name

So let's say you're changing the ids accordingly to "a-1", "a-2" etc. You can then make better use of selectors and run the matched items through an each loop (that will take care of the rest):

$('[EMAIL PROTECTED]"a-"]').each(function(i) {
    $(this).bind('click', function() {
        toggleTab(i);
    });
});

HTH,


--Klaus

Reply via email to