<分区>
目前这是我的 javascript 代码:
function GetEvents()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var eventObjects = JSON.parse(this.responseText);
var table = document.getElementById("EventsTable"); //Gets the Table in the HTMl
//Loops through the passed in array and adds each event in the table
for(i = 0; i < eventObjects.length; i++)
{
var startDate = new Date(eventObjects[i].eventStart);
var eventStart = startDate.getDate() + " / " + startDate.getMonth() + " / " + startDate.getFullYear();
var ID = eventObjects[i].eventID;
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = eventObjects[i].eventName;
cell2.innerHTML = eventStart;
cell3.addEventListener("click", function(){GetEventInfo(ID); });
//Adds Image to third cell;
var img = document.createElement('img');
img.src = "EventIcon.png"
cell3.appendChild(img);
}
}
}
xmlhttp.open("GET", "php/includes/GetEvents.php", true);
xmlhttp.send();
}
function GetEventInfo(eventID)
{
alert(eventID);
}
查看第一个函数,它所做的是使用从我的数据库收集的数据将单元格插入到我拥有的用于显示事件信息的 HTML 文件中。虽然我目前正在尝试做的是当我单击表中的这些事件之一时调用第二个函数,但它工作正常,并传入每个事件应具有的 eventID。
每个事件的 eventID 编号也是从数据库中收集的,所以我现在要做的是向每个事件添加一个 onclick 操作,该操作将运行“GetEventInfo”函数并传入相应的事件 ID。 到目前为止,我已经有了一个包含 ID 的变量:
var ID = eventObjects[i].eventID;
然后我用它来添加 onclick Action :
cell3.addEventListener("click", function(){GetEventInfo(ID); });
这会正确地执行 onclick 操作,当我点击它们时事件会运行该函数,但我遇到的问题是传入的 ID 对于每个事件都是完全相同的,所以无论我点击什么事件上,它将始终打印出它不应该打印的相同事件 ID,该事件 ID 要么是第一个事件,要么是最后一个事件。
有人知道为什么会这样吗?