我在这里想念什么?
我在html视图中有这个javascript:
sections.forEach(sec => {
const li = jQuery(`<li>${sec.categoryName}<button type="button" onclick="
if (confirm('Remove ${sec.categoryName}?')) removeSectionTapped(sec)"
>Remove</button></li>`);
jQuery('#Sections').append(li);
});
function removeSectionTapped(sec) {
console.log(sec)
}
在我按OK确认后,我得到此错误: Uncaught ReferenceError sec is not defined
sec是在确认消息中定义的,但是在if语句中没有定义。
您有两个名为的变量sec
,它们都被声明为函数参数的名称,因此对于这些函数而言是局部的。
您正在尝试在onclick
属性内使用变量。该属性不在这两个函数中(即使从中生成属性的HTML源代码也位于其中),因此该变量在使用时已超出范围。
不要使用onclick
属性,而是将事件处理程序与JavaScript绑定。
sections.forEach(sec => {
const li = jQuery("<li />");
li.append(sec.categoryName);
const button = jQuery('<button type="button" />');
button.text("Remove")
button.on("click", () => {
if (confirm(`Remove ${sec.categoryName}?`)) {
removeSectionTapped(sec);
}
});
li.append(button);
jQuery('#Sections').append(li);
});
function removeSectionTapped(sec) {
console.log(sec)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句