未捕获的TypeError。 indexOf不是函数错误

时间:2017-12-05 19:05:56

标签: javascript indexof

我是一名新手并且正在尝试创建js脚本以隐藏并在网页上显示可见的部分。以前的部分似乎工作正常。代码段的最后一部分返回此错误:

scripts.js:29 Uncaught TypeError: sections.indexOf is not a function
    at nextSection (scripts.js:29)
    at <anonymous>:1:1

有谁能告诉我我没有来这里?

/*
============================================
array of all sections
============================================
*/
var sections=document.querySelectorAll("section");

/*
============================================
Function to find the section that is being displayed (the one that doesn't have "not1st" as a class.)
============================================
*/

function findSection(){
for (var i=0; i<sections.length; i++) {
    if (sections[i].className.includes("not1st")){
        continue;
    } else {
        return sections[i];
    }}}

/*
============================================
Function to load the next section
============================================
*/

function nextSection() {
   sections[sections.indexOf(findSection())+1];
}

1 个答案:

答案 0 :(得分:8)

querySelectorAll没有返回数组,它会返回NodeListNodeList没有indexOf功能。

您可以使用Array.from将其转换为数组:

var sections = Array.from(document.querySelectorAll("section"));

...或没有Array.fromArray#slice的旧版浏览器:

var sections = Array.prototype.slice.call(document.querySelectorAll("section"));

有关详细信息,请参阅&#34;对于类数组对象&#34;我的另一个答案的一部分here