将JSON数组元素与事件处理程序相关联

时间:2016-08-01 21:45:14

标签: jquery json ajax

有没有办法,因为我遍历一个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()的所有事件处理程序都指向索引中的最后一个值。我可以以某种方式解决这个问题吗?

由于

2 个答案:

答案 0 :(得分:1)

使用$(this)将解决您的问题。不要混淆,但我也会使用$.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"));
});

答案 1 :(得分:0)

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

尝试

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