为什么.includes()不能与.classList一起使用? [英] Why doesn't .includes() work with .classList?

查看:167
本文介绍了为什么.includes()不能与.classList一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

element.classList 返回一个类数组,我的理解.includes()用于数组,所以我不明白为什么这不会工作,我知道我可以使用.contains()与classList,但我很好奇为什么.includes()不起作用。

element.classList returns an array of classes, its my understanding .includes() is used with arrays, so I don't understand why this wont work, I know I can use .contains() with classList but I'm curious as to why .includes() doesn't work.

两者都是数组,如果我输入这个例如它就不会工作

both are arrays, if I typed this for example it wont work

var li=document.createElement('li');
li.classList.add('main-nav');
li.classList.includes('main-nav');

但这将

var ary=['a','b','c'];
ary.includes('a');                               


推荐答案

Element.classList DOMTokenList 对象,虽然它在控制台中打印出类似数组的对象。但是如果你试试Firefox,它会返回 DOMTokenList [main-nav]

Element.classList is a DOMTokenList object, though it prints an array-like in console. But if you try on Firefox, it'd return DOMTokenList["main-nav"]

并且,< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes =noreferrer> includes 是方法 数组而不是 DOMTokenList

这就是为什么在你的情况下遇到 li.classList.includes不是函数的原因。

Which is why it's expected to encounter li.classList.includes is not a function in your case.

您可以使用 ES2015传播运算符将其转换为数组。

You can use ES2015 spread operator to cast it to be an array.

[...li.classList].includes('main-nav')

或者,您可以使用 DOMTokenList.contains 方法。

Or alternatively, you can use DOMTokenList.contains method.

li.classList.contains('main-nav')






为什么声明为包含而不是包含? (感谢@akinuri)


Why is it declared as includes instead of has or contains? (thanks to @akinuri)

提案


网络上有像 DOMStringList DOMTokenList
类似于数组,并且具有名为包含,其中
的语义与我们的包括。不幸的是,与那些
的网格划分不是网络兼容的。

The web has classes like DOMStringList and DOMTokenList which are array-like, and have methods named contains with the same semantics as our includes. Unfortunately, meshing with those is not web-compatible.

这篇关于为什么.includes()不能与.classList一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆