未捕获的类型错误。 indexOf 不是函数错误
Uncaught TypeError. indexOf is not a function error
我是一名菜鸟,正在尝试创建 js 脚本来隐藏和显示网页上的部分。前面的部分似乎工作正常。代码段的最后一部分 returns 这个错误:
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
不是 return 数组,它 return 是一个 NodeList
。 NodeList
s 没有 indexOf
函数。
您可以使用 Array.from
:
将其转换为数组
var sections = Array.from(document.querySelectorAll("section"));
...或对于没有 Array.from
、Array#slice
:
的旧版浏览器
var sections = Array.prototype.slice.call(document.querySelectorAll("section"));
有关详细信息,请参阅我的其他回答 here 的 "For Array-Like Objects" 部分。
我是一名菜鸟,正在尝试创建 js 脚本来隐藏和显示网页上的部分。前面的部分似乎工作正常。代码段的最后一部分 returns 这个错误:
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
不是 return 数组,它 return 是一个 NodeList
。 NodeList
s 没有 indexOf
函数。
您可以使用 Array.from
:
var sections = Array.from(document.querySelectorAll("section"));
...或对于没有 Array.from
、Array#slice
:
var sections = Array.prototype.slice.call(document.querySelectorAll("section"));
有关详细信息,请参阅我的其他回答 here 的 "For Array-Like Objects" 部分。