我的代码在 jsfiddle 上运行。代码如下。我可以打赌这是我在做一些愚蠢的事情,但我找不到它。
点击表示Uncaught ReferenceError:showDetail未定义
我也尝试过添加不同的参数,只是为了尝试排除故障。传递无、一、二不会影响错误消息。
const lcAppdata = {
matters: [{
mid: 100,
title: "Matter1",
dateOpened: "01/01/17",
decedent: "Elvis Presley",
personalRepresentative: "Alexis Texas",
attorneyAccountInfo: "John Holmes"
}, {
mid: 200,
title: "Matter2",
dateOpened: "01/02/16",
decedent: "Kurt Cobain",
personalRepresentative: "Kagney Linn Karter",
attorneyAccountInfo: "Simon Rex"
}, {
mid: 300,
title: "Matter3",
dateOpened: "01/03/15",
decedent: "Bob Marley",
personalRepresentative: "Nikki Benz",
attorneyAccountInfo: "Ron Jeremy"
}],
currentMatter: ''
};
function showDetail(mid){
console.log(mid);
};
function init(){
for(let matter of lcAppdata.matters){
$('#tbodyMatterList').append(`<tr
onclick="showDetail(${matter.mid})">
<th scope="row" >${matter.title}</th>
<td bind>${matter.decedent}</td>
<td bind>${matter.dateOpened}</td>
<td bind>${matter.personalRepresentative}</td>
<td bind>${matter.attorneyAccountInfo}</td></tr>`);
}
};
init();
最佳答案
你的代码很好,这是因为 jsfiddle 运行你的脚本的方式。它设置为运行脚本 onLoad
,即您的所有代码实际上都在 load
事件的回调内运行,因此您的函数 showDetail
实际上并未定义为全局函数,但仅限于加载事件回调本地
您可以更改代码以将 showDetail
函数附加到 window
对象,使其像这样全局化
function showDetail() {
console.log($(this).attr('data-mid'));
};
window.showDetail = showDetail;
或更改 jsfiddle 设置以像这样全局运行脚本
关于javascript - onclick 调用的方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46256381/