【问题标题】:Uncaught TypeError. indexOf is not a function error未捕获的类型错误。 indexOf 不是函数错误
【发布时间】:2017-12-06 03:08:56
【问题描述】:

我是一个菜鸟,正在尝试创建 js 脚本来隐藏和制作网页上的可见部分。前面的部分似乎工作正常。 sn -p 的最后一部分返回此错误:

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];
}

【问题讨论】:

  • 我知道最后一部分还没有完成,但我会一步一步地确保在我继续编写代码之前每一点都有效。
  • 因为你没有数组... querySelectorAll 是一个 HTML 集合。

标签: javascript indexof


【解决方案1】:

querySelectorAll 不返回一个数组,它返回一个NodeListNodeLists 没有 indexOf 函数。

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

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

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

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

有关更多信息,请参阅我的另一个答案here 的“For Array-Like Objects”部分。

【讨论】:

    猜你喜欢
    • 2014-08-19
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2019-06-06
    相关资源
    最近更新 更多