views:

14

answers:

2

I'm new to JQuery and I'm trying to use it to implement an enhancement in an old web application.

I'm gathering a list of strings from a server and rendering each one of them in its own anchor tag such that they appear in a comma delimited list. I assign that generated markup to a span's inner html:

$.getJSON("http://domain/restOfURL",
    function(data){
        var anchorString = "";
        $.each(data.companies, function(i,companies){                                    
            if (i > 0)
            {
                anchorString += ", ";
            }
            anchorString += '<a class="sr" href="#">' + companies + '</a>';
        });
        $("#anchorsListSpan").html(anchorString);
    });
});

All of that works and I can see the anchors on the live web page. The markup looks like this in Firebug:

<span id="anchorsListSpan">
    <a class="sr" href="#">ABC</a>
    ,
    <a class="sr" href="#">Apple</a>
    ,
    <a class="sr" href="#">Apollo</a>
</span>

The problem I'm having is that any generated anchors are not causing my click event to fire:

$("a.sr").click(function(){
    alert("link clicked");
});

I noticed that if I hard code similar anchors within that div that the click event does fire. For some reason the ones that I programmatically add won't cause the click event to fire.

Does anyone see what I'm doing wrong here?

Thanks for any help,

+2  A: 

Use live() instead of click():

$("a.sr").live("click", function(){
    alert("link clicked");
});
Šime Vidas
+2  A: 

Try using $("a.sr").live('click', function() {//...});

Aaron Hathaway