jquery动态添加.data()在选中时未定义

Doo*_*Dah 1 javascript jquery

我有以下代码,我在li元素上设置一些任意数据

function showCountries( data )
{
    for( var i in data )
    {
        var li = document.createElement('li');
        $(li).html( '<a>' + i + '</a><span>&gt;</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 ) );
    }
}
Run Code Online (Sandbox Code Playgroud)

后来,在选定的国家,我想获得货物数据.但是,它是未定义的

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
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么?这是在页面加载后动态设置.data()的问题吗?

谢谢,斯科特

Adr*_*iro 5

这一行:

var cargo = $(this).children('a').data('cargo');
Run Code Online (Sandbox Code Playgroud)

应改为:

var cargo = $(this).data('cargo');
Run Code Online (Sandbox Code Playgroud)

您可以在li元素中设置数据,而不是在子元素中a.