gpt4 book ai didi

javascript - 未定义 Uncaught ReferenceError

转载 作者:行者123 更新时间:2023-12-01 00:49:10 25 4
gpt4 key购买 nike

我在这里错过了什么?

我在 html View 中有这个 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)
}

在确认上按“确定”后,我收到此错误:未定义 Uncaught ReferenceError sec

sec 在确认消息中定义,但在 if 语句中没有定义。

最佳答案

您有两个名为 sec 的变量,它们都被声明为函数参数的名称,因此对于这些函数来说是本地变量。

您正尝试在 onclick 属性内使用变量。该属性不在这两个函数的内部(尽管生成该属性的 HTML 源代码在内部),因此该变量在使用时超出了范围。

不要使用 onclick 属性,而是使用 JavaScript 绑定(bind)事件处理程序。

 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)
}

关于javascript - 未定义 Uncaught ReferenceError ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57127500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com