1

i'm using ajax to get some information to my page

the information received in an array so i use for loop to append them to my html page in this way :

for i to i less than my information  i++

$('#ul').append("<li>"+info[i]+"</li>");

but i want to add a different .click event to every 'li' tag but i don't want to loop another time for this. is there any simple way to do this ?

I tried those solutions but nothing seems to work :

A)

for i to i less than my information  i++

$('#ul').append(   $("<li>"+info[i]+"</li>").click(function(){alert(i)})    );

return the last "i" value for all of them

B)

for i to i less than my information  i++

$('#ul').append("<li>"+info[i]+"</li>").find('li:last-child').click( function( {alert(i)} )    );

return also the last "i" value for all of them

is there any simple way to do this ?

trrrrrrm
  • 11,362
  • 25
  • 85
  • 130

5 Answers5

2

The following has been tested, and works as expected:

info = ["Jonathan","Sampson","Programming"];

$(info).each(function(i){
  $("<p>"+info[i]+"</p>").click(function(){
    alert(i);
  }).prependTo("body");
});
Sampson
  • 265,109
  • 74
  • 539
  • 565
2
$.each(info, function() {
  $("<li></li>").text("...").click(function() {
    // do stuff
  }).appendTo("#ul");
});
cletus
  • 616,129
  • 168
  • 910
  • 942
1

at the time of click, i will be set as the last item in the loop. So you have to store the data on the li, something like this:

$('#ul').append(   $("<li>"+info[i]+"</li>").data('num',i).click(function() {alert($(this).data('num'));})    );
honeybuzzer
  • 139
  • 4
0

The problem you are having is accessing the variable i in the callback, which is a closure.

Here's a related SO question that will help you. I think you can also use the jQuery .each() feature from the 2nd code snippet in the accepted answer:
Access outside variable in loop from Javascript closure

The linked "closure" page also describes your problem exactly:
http://matthew-marksbury.blogspot.com/2008/12/javascript-closures-and-scope.html

Community
  • 1
  • 1
Brian Pan
  • 144
  • 1
  • 8
0

try this will be better

// bind event here only once!:

$(function(){
    $("#parent>li").live("click", function(){
    alert( $(this).html() );        
});    

// your data
var info = ["a", "b", "c"];

var list = [];
$.each(info, function(index, item){
    list.push("<li>");
    list.push(item);               
    list.push("</li>");               
});

$("#parent").append( list.join("") );


// you page like this(it has an id property):

<ul id="parent"></ul>
www
  • 4,065
  • 7
  • 30
  • 27