gpt4 book ai didi

Javascript:即使我使用的是 window.onload,我也会收到错误 'var is not defined'

转载 作者:行者123 更新时间:2023-11-30 13:46:37 27 4
gpt4 key购买 nike

我正在尝试创建一个带有按钮的网站,该按钮可以转到下一页并调用 main.js 中的函数,暂时忽略下一页导航。

我的 HTML 按钮代码是什么样的:

<button onclick="resetAll()" id="beginButton" class="float-left submit-button"><h3>Begin</h3></button>

我的 JS 代码是什么样的:

window.onload = function() {
function resetAll() {
// some resets and a log to show me it's been reset
console.log("All reset");
}
}

我希望代码运行我的 js 文件,直到它找到函数“resetAll()”,但我却收到错误 Uncaught ReferenceError: resetAll is not defined at HTMLButtonElement.onclick。我想让这个按钮链接到 js 文件,这样我的 HTML 就不会被其中的 js 代码弄乱。

我也试过使用代码

document.getElementById('beginButton').onclick = resetAll();

但这似乎在页面加载时运行。据我所知,window.onload 应该确保在加载整个 HTML 页面之前定义该函数。我的 HTML 脚本标签在我的 HTML 代码的头部,所以在按钮的声明之上。

谁能帮我解决这个问题?因为我一直卡在这些问题上..

最佳答案

将其从 window.onload(它有自己的作用域)中移除 - 并移除 ():document.getElementById('beginButton').onclick = resetAll;

或者将 onclick 移到里面:

window.onload = function() {
document.getElementById('beginButton').onclick = function() {
// some resets and a log to show me it's been reset
console.log("All reset");
}
}

推荐

window.addEventListener("load", function() {
document.getElementById('beginButton').addEventListener("click", function(e) {
e.preventDefault(); // remove if you want the button to submit
// some resets and a log to show me it's been reset
console.log("All reset");
}
}

关于Javascript:即使我使用的是 window.onload,我也会收到错误 'var is not defined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59200510/

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