2016-08-01 73 views
0

有没有办法,因为我迭代通过JSON文件关联某些数组元素与点击处理程序的列表?关联JSON数组元素与事件处理程序

什么我是这样的:

$.ajax(
{ 

    url: 'json/data.json', 
    dataType : 'json', 
    type: 'get', 
    cache: false, 
    success: function(fullJSONData) 
    { 
     $(fullJSONData.events).each(function(index, oneJSONLine) 
     { 
     $('#eventList').append(newEvent(index, oneJSONLine)) 
     $("#eventItem" + index).on("click", showEvent (fullJSONData.events[index])); 
     }); 
    }, 
    error: function (e) 
    { 
     console.log("error " + e.message); 
    } 

}); 

这不是工作,因为所有的showEvent事件处理程序()指向的最后一个值,这是在指数。我能以某种方式解决这个问题吗?

谢谢

回答

0

您正在调用该函数,而不是作为参考传递它。

尝试

$(fullJSONData.events).each(function(index, oneJSONLine) { 
    $('#eventList').append(newEvent(index, oneJSONLine)) 
    $("#eventItem" + index).on("click", function() { 
     showEvent(fullJSONData.events[index]); 
    }); 
}); 
+0

感谢那@charlietfl,很好的学习差异 – Scone

1

使用$(这)将在这里解决您的问题。不要混淆,但我也会使用$.dataevent delegates。另外请注意,我一次选择'#eventList'项目以避免在每次迭代中重新选择它。

var eventList = $('#eventList'); 

$(fullJSONData.events).each(function(index, jsonLine) 
{ 
    $(this).data("jsonData", jsonLine); 
    eventList.append("<li>" + jsonLine.[some property for text] + "</li>"); 
} 

eventList.on("click", "li", function() 
{ 
    showEvent($(this).data("jsonData")); 
}); 
相关问题