Without testing it, off the top of my head I think it may be the .wrap()
that is doing you in. That has to remove the element from the DOM and
re-insert it, and I think that loses the event binding.

Also, I take it that $dsanchors refers to a UL, is that right? Then you're
temporarily inserting the A element directly into the UL, which is invalid.
Maybe browsers allow it anyway, but there's no guarantee what they will do.

I would try this instead:

    $('<a>' + linkText + '</a>')
        .attr({
            'href': '#' + index,
            'id': index,
            'class': linkText == selected ? 'selected' : 'notSelected'
        })
        .wrap('<li></li>')
        .appendTo($dsanchors);
        
    $('#'+index).bind('click', function() {
        alert("hi");
        return false;
    });

-Mike

> -----Original Message-----
> From: jquery-en@googlegroups.com 
> [mailto:jquery...@googlegroups.com] On Behalf Of Alexandre Plennevaux
> Sent: Saturday, January 03, 2009 2:20 PM
> To: Jquery-en
> Subject: [jQuery] event binding issue
> 
> 
> hello friends,
> 
> i'm injecting a menu ( UL > LI > A markup) and binding each A 
> anchor a click event, but the event fails to trigger. Can you 
> explain me what i'm dooing wrong?
> 
> here is the code sample:
> 
>  $('<a>' + linkText + '</a>').appendTo($dsanchors).attr({
>                 'href': '#' + index,
>                 'id': index,
>                 'class': (linkText == selected) ? 'selected' 
> : 'notSelected'
>             }).bind('click', function()
>             {
> 
>                 alert("hi");
> 
>                 return false;
>             }).wrap('<li></li>');
> 
> 
> the html is correctly injected, but the event is not attached.
> 

Reply via email to