为什么我不断获取.addEventListener不是一个函数? [英] Why do I keep getting .addEventListener is not a function?

查看:69
本文介绍了为什么我不断获取.addEventListener不是一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在与JW Player一起使用,并且除我正在使用的一项功能外,其他所有功能都运行良好.当我运行代码时,出现控制台错误:未捕获的TypeError:upTop.addEventListener不是一个函数 n

So I'm working with a JW Player and everything is working great except for one piece of functionality I'm working on. When I run the code I get a console error: Uncaught TypeError: upTop.addEventListener is not a function

这是代码:

                var upTop = document.getElementsByClassName('playlist-item');

                upTop.addEventListener('click', function() {
                jwplayer.setup({autostart: true, floating: {dismissable: true}});
                       window.scrollTo(0, 0);
                });

这里是否缺少某种语法错误?

Is there some kind of syntax error I'm missing here?

推荐答案

调用getElementsByClassName的工作方式不同于getElementById.多个元素可以具有相同的类名,因此返回的是一个数组.例如,如果您要返回第一个项目是因为您知道类中只有一个元素,那么

Calling getElementsByClassName works differently from getElementById. Multiple elements can have the same class name so what is returned is an array. For example, if you want the first item returned because you know there is only one element with the class then

var upTop = document.getElementsByClassName('playlist-item')[0];

就足够了.否则,您可以遍历upTop中的所有项目并将事件侦听器添加到所有这些项目中.在纯JS中:

would suffice. Otherwise, you can loop through all items in upTop and add the event listener to all of them. In pure JS:

for (var i=0; i < upTop.length;i++) {
 upTop[i].addEventListener('click', function() {
    wplayer.setup({autostart: true, floating: {dismissable: true}});
    window.scrollTo(0, 0);
 });
}

这篇关于为什么我不断获取.addEventListener不是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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