Javascript-无法使"getElementsByClassName"正常工作 [英] Javascript - Can't get 'getElementsByClassName' working

查看:134
本文介绍了Javascript-无法使"getElementsByClassName"正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清为什么我的代码无法正常工作.这是JS的一部分:

Im struggling to figure out why my code is not working. Here is part of the JS:

function init() {
    var showMenu = document.getElementsByClassName('showMenu'),
        perspectiveWrapper = document.getElementById( 'perspective' ),
        container = perspectiveWrapper.querySelector( '.container' ),
        contentWrapper = container.querySelector( '.wrapper' );

    showMenu.addEventListener( clickevent, function( ev ) {
        ev.stopPropagation();
        ev.preventDefault();
        docscroll = scrollY();
        // change top of contentWrapper
        contentWrapper.style.top = docscroll * -1 + 'px';
        // mac chrome issue:
        document.body.scrollTop = document.documentElement.scrollTop = 0;
        // add modalview class
        classie.add( perspectiveWrapper, 'modalview' );
        // animate..
        setTimeout( function() { classie.add( perspectiveWrapper, 'animate' ); }, 25 );
    });
}

这是HTML的一部分:

Here is part of the HTML:

<div id="topBar">
    <h1>Company</h1>
    <a href="#" class="entypo-menu showMenu"></a>
</div>

<div class="line"></div>

<div id="fixedBar">
    <h1>Company</h1>
    <a href="#" class="entypo-menu showMenu"></a>
</div>

由于某些原因,当我加载页面时,出现此错误:

For some reason when I load the page, I get this error:

TypeError: undefined is not a function (evaluating 'showMenu.addEventListener')

我不明白这一点,因为如果我更改此行:

I don't understand this because if I change this line:

var showMenu = document.getElementsByClassName('showMenu'),

收件人:

var showMenu = document.getElementById( 'showMenu' ),

它确实有效!

为什么类选择器不起作用,而id one起作用?我正在尝试获取与类showMenu的两个链接以执行JS.

Why won't the class selector work but the id one will? I'm trying to get both links with the class showMenu to perform the JS.

推荐答案

(确切地说,是HTMLCollection )所有与类名匹配的 all 元素.您可能在乎第一个元素,因此请尝试使用以下内容:

document.getElementsByClassName returns an array-like list (an HTMLCollection, to be exact) of all elements that match the class name. You probably care about the first element, so try using the following instead:

var showMenu = document.getElementsByClassName( 'showMenu' )[0],

如果您关心所有元素,则需要遍历所有元素:

If you care about all of the elements, you'll need to loop through the elements:

var showMenu = document.getElementsByClassName( 'showMenu' ),

// ...

for ( var i = 0; i < showMenu.length; ++i ) {
    showMenu[i].addEventListener( clickevt, function( ev ) {
        // Your code here
    });
}

这篇关于Javascript-无法使"getElementsByClassName"正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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