我等待检索数据,然后将数据添加到表中并尝试使用以下代码向每行添加click事件。
scope.$watch(attrs.aaData, function(value) {
var completeData = scope.$eval(attrs.allData);
var dataTable = element.dataTable(options);
var val = value || null;
if (val) {
dataTable.fnClearTable();
dataTable.fnAddData(scope.$eval(attrs.aaData));
var table = document.getElementsByClassName("dataTable")[1];
for (var i = 0, row; row = table.rows[i]; i++) {
console.log(row);
console.log(completeData[i]);
$(row).click(function(){
window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
})
// javascript for click, but there should be a ng-click way
// $(row).attr('ng-click', 'changeView(/dashboard/patients/1)');
};
}
控制台日志确认行,并且completeData [i]返回正确的值(并且completeData [i])具有我想要的patient_id组件。然而,当我点击任何一行时,我收到以下错误:
Uncaught TypeError: Cannot read property 'patient_id' of undefined
有什么想法吗?
答案 0 :(得分:1)
问题是scoping issue。您需要将事件处理程序包装在闭包中。
for (var i = 0, row; row = table.rows[i]; i++) {
(function(i) {
console.log(row);
console.log(completeData[i]);
$(row).click(function(){
window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
})
// javascript for click, but there should be a ng-click way
// $(row).attr('ng-click', 'changeView(/dashboard/patients/1)');
})(i);
}
因为现在,这一行:
$(row).click(function(){
window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
})
始终会将i
引用到i
的当前值,而不是定义函数时的值。
或者,我建议使用jquery的$.each
来清理你的循环并同时构建一个闭包:
$.each(table.rows, function(i, row) {
console.log(row);
console.log(completeData[i]);
$(row).click(function(){
window.location.hash = '#/dashboard/patients/' + completeData[i].patient_id;
})
// javascript for click, but there should be a ng-click way
// $(row).attr('ng-click', 'changeView(/dashboard/patients/1)');
});