2016-08-01 32 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")); 
}); 
相關問題