Wednesday, 28 August 2013

JQuery for loop stuck at last index

JQuery for loop stuck at last index

I have function process_row that appends tags to html, and those tags are
chained to a function upon clicked. (in this case, simply alert(i), its
position in the result array).
But however, upon being clicked, the newly generated alerts the length of
the entire result array. I have tried many, many changes to try and make
it work, but it doesn't.
Strange thou, fab_div.attr("id", result_data[0]); works fine !! In Chrome
inspect element the id tags are displayed as they are, but the click
function points everything to the last element in the array.
for example, if I do, fab_div.click(function () { alert(result_data[0])
});, I get the name of the LAST element in the array, doesn't matter which
element was clicked.
can anyone please explain to me... WHY??
I think it may have something to do with $("<div>") where JQuery thinks
it's the same div that it's assigning to. Is there any way around this?
The 's are generated dynamically and I would not want to let PHP do the
echoing. Plus the content may be updated realtime.
Example dataset :
Smith_Jones#Smith#Jones@janet_Moore#Janet#Moore@Andrew_Wilson#Andrew#Wilson
After many, many changes, still not working:
function process_row(data){
result_array = data.split("@");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>");
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
fab_div.append(fab_text)
// fab_div.click(function () { alert(i) });
// ^ not working, try appending list of id's to id_list
id_list.push(result_data[0])
$('#ls_admin').append(fab_div)
}
for(j = 0; j < id_list.length; j++){
$('#' + id_list[j]).click(function () { alert(j) })
}
}
}
Original Attempt:
function process_row(data){
result_array = data.split("@");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>").append(fab_text).click(function () {
alert(i) });
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
$('#ls_admin').append(fab_div)
}
}
}

No comments:

Post a Comment