I have the following code where I am setting some arbitrary data on a li element
function showCountries( data )
{
for( var i in data )
{
var li = document.createElement('li');
$(li).html( '<a>' + i + '</a><span>></span>' );
$(li).data('cargo', { state: data[i] });
/*
right here, if I look at $(li).data('cargo').state in the debugger
I see the data as expected
*/
$('#countries').append( li );
$(li).on('click', $.proxy( countrySelected, li ) );
}
}
Later, in country selected, I want to get the cargo data. But, it is undefined
function countrySelected()
{
var country = $(this).children('a').html();
// country is what I expect
var cargo = $(this).children('a').data('cargo');
// cargo is undefined here
// I tried this too:
var cargo = $('#countries li.selected a').data('cargo');
// cargo is undefined here as well
}
What I am doing wrong? Is this an issue with the .data() being set dynamically after the page is loaded?
Thanks,
Scott
This line:
should be changed to this:
You set the data in the
lielement, not in the childa.