Javascript ES6“不是函数”错误

时间:2016-12-13 16:48:14

标签: javascript function dom

我一直在研究一些使用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

2 个答案:

答案 0 :(得分:0)

使用Array.from()Document.querySelectorAll()返回的NodeList转换为Array。然后,您可以在.forEach()的剩余时间使用input链接到javascript

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

答案 1 :(得分:0)

首先,要仔细检查两件事:

  1. 您是否在DOM完成解析之前运行此函数?如果是这样,请将此代码包装在DOMContentLoaded事件侦听器中,如下所示:

    document.addEventListener('DOMContentLoaded', function() {
        //code here
    });
    
  2. 您的浏览器环境是否支持DOM NodeLists上的forEach方法。要查看,console.log(NodeList.prototype.forEach);您应该得到类似:function forEach() { [native code] },如果没有,则不支持,因此您的错误。

  3. 为了不支持NodeList.forEach,你可以试试这个:

    var inputs = [].slice.call(document.querySelectorAll('.controls input'));
    

    现在将输出一个元素数组而不是NodeList,并允许您访问Array.prototype函数