I have created an array object with some dummy properties, I have have also dynamically created some list items that I would like to attach a click handler to. When a list item is clicked I would like to present the appropriate data inside #container using the template Ive set up. Im assuming I can use the index from the for loop of dynamic list items and some how use this to show the correct object properties? If you could advise me where I have gone wrong with this that would be great, sorry but Ive lost my way a little with this.
$(document).ready(function () {
var data = [
{
name: 'kyle',
age: 23,
sex: 'male'
}, {
name: 'james',
age: 19,
sex: 'male'
}, {
name: 'catrina',
age: 28,
sex: 'female'
}];
var template = $('#template').html();
// Links created dynamically
for (var i = 0; i < 3; i++) {
var link = '<li>Link ' + i + '</li>';
$('#links').append(link);
}
// When li is clicked show related data properties, li[0] = data[0], li[1] = data[1] ...
$('li', '#links').live('click', function (e) {
$.each(data, function (index, value) {
$('#container').append(data.name[i], data.age[i], data.sex[i]);
});
$('#container').html(data);
});
});
Code can be found here http://jsbin.com/otirax/6/edit
The easiest thing is to add a data item to each link when you create it that contains the index. You can then fetch that index later upon click:
Then, in your click handler, you can retrieve that value:
This way of storing and then retrieving the index provides a permanent index value set on each
liat the time you create it. If you will never reorder thelitags and they are the only objects at that level, you can simplify it a bit by using the .index() jQuery method that will calculate the index for a givenlitag dynamically when needed by just counting how many siblings come before it:FYI,
.live()has been deprecated and one should use.on()for jQuery 1.7+ or.delegate()for earlier versions of jQuery.Your
.live()code would be this with.on():