这段代码运行良好。我的 IDE (RubyMine) 认为没有问题。但 Chrome DevTools 在源代码和控制台中都会引发错误。有什么办法可以清理这个吗?
Uncaught TypeError: process is not a function
$(document).ready(function () {
let buttonWatch = function (process) {
$(this).off('click');
alert(typeof(process)); // This alerts "function"
process(); // The error is thrown here
return $(this).on('click', buttonWatch);
};
$("#loginButton").on('click', function () {
function process() {
alert("Running a process.");
}
buttonWatch(process);
});
});
按照建议修改的代码显示了相同的问题:
let myProcess;
let process;
$(document).ready(function () {
let buttonWatch = function (process) {
$(this).off('click');
alert(typeof(process)); // alerts "function"
process(); // Error thrown here
return $(this).on('click', buttonWatch);
};
$("#loginButton").on('click', function () {
function myProcess() {
alert("Running a process.");
}
buttonWatch(myProcess);
});
});
最佳答案
正如我反复指出的,代码运行良好。我只从 DevTools 收到奇怪的错误。无论如何,通过使用分配可以消除错误,DevTools 很高兴。
$(document).ready(function () {
let buttonWatch = function (process) {
$(this).off('click');
alert(typeof(process)); // This alerts "function"
let result = process(); // No error is thrown
return $(this).on('click', buttonWatch);
};
$("#loginButton").on('click', function () {
function process() {
alert("Running a process.");
}
buttonWatch(process);
});
});
这里的问题是,因为返回时必须重新实例化单击监听器,所以我无法返回该过程的结果。因此,我使用禁用方式编写了一个更好的解决方案,而不是完全关闭监听器。
$(document).ready(function () {
let buttonWatch = function (button, process) {
$(button).prop("disabled", true);
let result = process();
$(button).prop("disabled", false);
return result;
};
$("#loginButton").on('click', function () {
function buttonProcess() {
alert("Running a process.");
}
buttonWatch(this, buttonProcess);
});
});
为了完整起见,可以在传递参数并要求返回进程结果时使用此设置:
$(document).ready(function () {
// buttonWatch disables and enables clicks around a process
let buttonWatch = function (button, process) {
$(button).prop("disabled", true);
let result = process();
$(button).prop("disabled", false);
return result;
};
$("#loginButton").on('click', function () {
function buttonProcess(message) {
alert(message);
return false
}
buttonWatch(this, function(){return buttonProcess("Running a process.")});
});
});
关于Javascript传递函数并收到错误: Uncaught TypeError,进程不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43748539/