-1
        for ( var i = 0; i < contentCount; i++ )
        {
            var farm_id = _newspaperData[i]['farm_id'];

            //console.log(farm_id )
            $('#news_item_' + i).html(
                '<input type="hidden" value="' + farm_id + '" id="#news_item_farm_id_' + i + '" />' +
                '<div class="author" style="position: absolute; top: 2px; left: 2px"></div>' + 
                '<div class="item" style="position: absolute; bottom: 2px; right: 2px">' + 
                    '<div class="icon_' + _newspaperData[i]['product_varname'] + ' bg_64x64" style="position:relative; height: 90px;width: 120px;">' +
                        '<div class="stroke-shadow-black" style="position: absolute; top: 0; left: 10px; font-size: 30px">' + $.number( _newspaperData[i]['product_amount'] ) + 'x</div>' + 
                        '<div class="stroke-shadow-black" style="position: absolute; bottom: 0; right: 10px; font-size: 22px">' + $.number(  _newspaperData[i]['product_price'] ) + ' Coin</div>' + 
                    '</div>' + 
                '</div>' ).click(function()
                {
                    //console.log(farm_id )
                    new Roadside().getOtherRoadside(farm_id)
                });
        }

当我单击每个元素时,farm_id 值将与循环的最后一个相同。

似乎点击功能没有得到每个循环的farm_id值

4

1 回答 1

1

通过环绕另一个函数将变量发送到函数。

for ( var i = 0; i < contentCount; i++ )
{
    var farm_id = _newspaperData[i]['farm_id'];

    //console.log(farm_id )
    $('#news_item_' + i).html(...)
    .click(function(farm_id){
        return function()
        {
            //console.log(farm_id )
            new Roadside().getOtherRoadside(farm_id)
        }
    }(farm_id));
}

阅读此 SO 帖子以获取更多信息 -处理来自多个 AJAX JQuery 查询的独立数据

于 2013-09-11T20:11:15.070 回答