gpt4 book ai didi

javascript - 未捕获的类型错误 : Illegal invocation on callback

转载 作者:行者123 更新时间:2023-12-02 17:07:35 27 4
gpt4 key购买 nike

function submit() {
console.log('Submit!');
}

function foo(callback, param) {

console.log(callback);

// ... //

callback(param); // <-- Script fails here

}

<input type="button" onclick="foo(submit)">

为什么这不起作用?

function submit() { [native code] } foo.js:241
Uncaught TypeError: Illegal invocation

最佳答案

内在事件属性(如onclick)具有奇怪的范围规则,我并不假装完全理解。

属性内的 submit是输入所属表单元素的 submit 属性

或者:

  • 显式传递window.submit
  • 将函数重命名为其他名称​​或
  • 使用 JavaScript 而不是 HTML 绑定(bind)您的事件处理程序。

我会去the latter route我自己遵循一般原则(借此机会停止使用全局变量),并考虑重命名该函数以尽量减少困惑。

<input type="button">
<script>
// Scoping IIFE omitted from this simplified example
var button = document.getElementsByTagName('button')[0];
button.addEventListener("click", function () { foo(submit); });

function submit // etc etc
</script>

关于javascript - 未捕获的类型错误 : Illegal invocation on callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25107471/

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