tags:

views:

63

answers:

3

Consider the following code, in theory the click event should bind to each element but for some reason (unbeknown to me) it will only bind to the last link. does anyone have any ideas?

$.each(data, function(i,aitem){ 
linkid = 'address'+i;     
$("#SearchResults").html($("#SearchResults").html()+'<p><a id="'+linkid+'" href="#">'+ aitem.Address +'</a></p>');       
$('#'+linkid).bind("click", function(){
 otherfunction(i);
 return false;
});

});

+1  A: 

What about adding a live click-event?

$("a[id^=address]").live("click", function() {
    alert("ran");
    var value = $(this).attr("id").substr(7);
    myFunction(value);
    return false;
});

should add a click event to all those links (:

edit: Included tip from darin...

peirix
Thanks for your answer, however I need to call a function inside the bind event with the value of i in it, therefore iterating the links after they have been displayed isnt possible as I need the value of the result in the json object
Nick
I have updated the example to reflect this
Nick
As far as I can see the "id" of the anchor element is constructed by concatenating the "address" string with the value of "i" so you should be able to extract the value of "i" inside the click handler from the element id.
Darin Dimitrov
+1  A: 

this is a common problem with people who are new to closures.

the correct solution would be to do this:

$.each(data, function(i,aitem){ 

  linkid = 'address'+i;                                   
  $("#SearchResults").html($("#SearchResults").html()+'<p><a id="'+linkid+'" href="#">'+   aitem.Address +'</a></p>');                                        
  $('#'+linkid).bind("click", function(){
     (function(i){
        otherfunction(i);
        return false;
     }(i));
  });


});
mkoryak
What exactly does appending (varname) on the end of a pair of brackets do?
Nathan Taylor
Thanks for your answer however this yields the same result as the above, I had previously written it like that following an article I found, but to no avail.
Nick
+1  A: 

try:

var linkid = ...;
var link = $("<a></a>").attr('id', linkid).attr('href', '#').text(aItem.Address).click(function(){ alert('ran'); return false; });


$('#SearchResults').append(link.wrap("<p></p>"));

The idea being that you want to bind your click event to each link that you are creating, so just chain it to the end of your creation code, and be explicit about it.

Hope that helps.

casademora
Thank you, this fixed it!
Nick