gpt4 book ai didi

JavaScript ES6 "not a function"错误

转载 作者:行者123 更新时间:2023-11-28 05:14:07 29 4
gpt4 key购买 nike

我一直在编写大量使用 ES6 的 JavaScript 教程。到目前为止,两个类都抛出了相同的错误,而且作为 JavaScript 新手,我仍在尝试理解逻辑,因此不太擅长调试。我尝试使用 Babel 将 ES6 代码转换为纯 JavaScript,认为这是浏览器问题,但出现了同样的错误。

任何帮助将不胜感激。

ES6 JavaScript

const inputs = document.querySelectorAll('.controls input');

function handleUpdate() {
const suffix = this.dataset.sizing || '';
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}

inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));

“Babel”编译的 JavaScript

var inputs = document.querySelectorAll('.controls input');
function handleUpdate() {
var suffix = this.dataset.sizing || '';
document.documentElement.style.setProperty('--' + this.name, this.value + suffix);
}

inputs.forEach(function (input) {
return input.addEventListener('change', handleUpdate);
});

inputs.forEach(function (input) {
return input.addEventListener('mousemove', handleUpdate);
});

错误

inputs.forEach is not a function

最佳答案

使用Array.from()转换Document.querySelectorAll()返回的NodeList数组。然后,您可以在 javascript 的其余部分使用链接到 input.forEach()

const inputs = Array.from(document.querySelectorAll('.controls input'));

关于JavaScript ES6 "not a function"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41126365/

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