我有以下代码,我在 li 元素上设置一些任意数据
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 ) );
}
}
后来,在选择的国家,我想得到货物数据。但是,它是未定义的
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
}
我做错了什么?这是在页面加载后动态设置 .data() 的问题吗?
谢谢,斯科特