JavaScript - ReferenceError:事件未在addEventListener()

时间:2015-08-23 01:37:12

标签: javascript javascript-events

当我尝试加载我正在处理的HTML文档时,我一直收到此错误:ReferenceError: event is not defined。它指向文档的javascript中的addEventListener()行。我试图避免 jQuery,如果可能的话。因此,我使用document.getElementsByClassName().addEventListener()代替$(".className").click()

此外,我还要确认这个问题:

  1. addEventListener()是从getElementsByClassName()拨打的有效方法,还是......
  2. 我是否需要使用forEach()方法将addEventListener()方法一次附加到每个元素对象上?
  3. 相关的Javascript(非常不完整,因为它应该使一些主要的div显示/消失,并且我在将所有内容添加到页面后实现该功能的最后一次):

    document.getElementsByClassName("NavbarButton").addEventListener(
        "click",
        JumpToSection(event.target.innerHTML)
    );
    
    function JumpToSection(Section)
    {
        /*
            TO DO:
            Figure out how to toggle visibility of main sections
            The selected section needs to have visibility turned on & all others turned off
            May be doable with a loop and an if-else statement
        */
    
        // Set the URL to include the viewed section ONLY IF the function's input parameter is NOT BLANK
        // EXTREMELY optimized solution found here:
        // http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript
        if(!!Section) location.hash = Section;
    
        // Make sure the page is scrolled to the top
        window.scrollTo(0,0);
    
        // To be used a bit later on for looping through the sections & toggling visibility
        var AllSections = document.getElementsByClassName("Section");
    }
    

    在我试图添加事件监听器的HTML中(现在,我只在其中一个Navbar按钮上进行测试;一旦它工作,我可以删除onclick=""来自其他人的属性):

    <div id="TopBar" class="grid_32">
        <div id="CharName" class="grid_8 alpha">Calyo Delphi</div>
    
        <ul id="NavBar" class="grid_24 omega">
            <li id="ImagesButton"  class="NavbarButton grid_6 alpha">IMAGES</li>
            <li id="DetailsButton" class="NavbarButton grid_6"       onclick="JumpToSection(this.innerHTML)">DETAILS</li>
            <li id="FormsButton"   class="NavbarButton grid_6"       onclick="JumpToSection(this.innerHTML)">FORMS</li>
            <li id="StatsButton"   class="NavbarButton grid_6 omega" onclick="JumpToSection(this.innerHTML)">STATS</li>
        </ul>
    </div>
    

    我在SO上搜索过类似的其他问题,但似乎我已经将事件传递给被调用的函数,就像我应该做的那样......?所以我不知道我错过了什么......

1 个答案:

答案 0 :(得分:2)

在javascript中,您必须将事件附加到getElementsByClassName

返回的每个节点

喜欢这个

var classes=document.getElementsByClassName("NavbarButton");

for(var i=0;i<classes.length;i++)
    classes[i].addEventListener('click', JumpToSection);

function JumpToSection(event){
  console.log(event.target.innerHTML);
}