2015-02-07 3 views
4

내 코드가 작동하지 않는 이유를 파악하는 데 어려움을 겪고 있습니다.Javascript - 'getElementsByClassName'이 작동하지 않음

다음
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의 일부입니다 : 다음은 JS의 일부입니다

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

I :

<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> 

내가 페이지를로드 할 몇 가지 이유를 들어,이 오류가 발생합니다 이 줄을 변경하면 이해할 수 없습니다.

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

to :

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

작동하지 않습니다!

클래스 선택기가 작동하지 않지만 ID가 작동하지 않는 이유는 무엇입니까? JS를 수행하기 위해 클래스 showMenu과 함께 두 링크를 가져 오려고합니다.

답변

5

document.getElementsByClassName모두 요소가 클래스 이름과 일치하는 배열 형식의 목록 (정확히는 HTMLCollection)을 반환합니다. 당신은 아마 첫 번째 요소에 대한 관심, 그래서 대신 다음 사용해보십시오 :

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

// ... 

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

때문에 : 당신은 모든 요소에 대해 관심이 있다면, 당신은 요소를 통해 루프해야합니다

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

document.getElementsByClassName()은 배열과 비슷한 node list을 반환합니다.

목표로하려는 요소가 여러 개인 경우 for 루프 또는 .forEach()을 사용하여 루프를 반복해야하지만이 클래스의 n 번째 요소 만 찾는 경우에는 다음과 같이 색인을 지정할 수 있습니다. 브라켓 표기법 :

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

왜냐하면 getElementsByClassName return an array-like object of DOM elements입니다.

for (var i = 0; i < showmenu.length; i++) { 
    showMenu[i].addEventListener(clickevent, function(ev) { 
     // ... 
    }); 
} 

.. 또는 :

Array.prototype.forEach.call(showMenu, function(el, i) { 
    el.addEventListener(clickevent, function(ev) { 
     // ... 
    }); 
}); 

은 각 요소에 액세스하고 개별적으로 이벤트 리스너를 연결해야합니다

관련 문제