2014-09-10 5 views
-1
function Popup() { 

} 

Popup.prototype.openPopup = function() { 
    var div = document.getElementById("test"); 
    div.style.display = 'block'; 
     }; 

Popup.prototype.closePopup = function() { 
var div = document.getElementById("test"); 
div.style.display = 'none'; 
}; 


window.onload = function() { 
    var popup = new Popup(); 

    var opnpopup = document.getElementsByClassName('clck'); 
    opnpopup.addEventListener('click', function() { 
     popup.openPopup(); 
    }); 

    var cnclpopup = document.getElementById('cancel'); 
    cnclpopup.addEventListener('click', function() { 
     popup.closePopup(); 
    }); 


} 

HTML 코드 : 우리는 'ID'를 통해 액세스 할 때 내가 팝업이 표시되지 document.getElementsByClassName('clck')를 사용하여 클래스 이름 'clck'에 액세스하지만, 위의 JS에서프로토 타입 JS를 사용하여 클래스 속성에 액세스하려면

<button id="clck" class="clck">click here</button> 
<div id="test" class="popup"> 
    This is a test message 
    <div id="cancel" class="cancel" ></div> 
</div> 

그때 그것은 작동합니다. 그래서 문제가 설명해주세요.

+1

PrototypeJS를 사용하고 있습니까? jQuery처럼 다른 많은 것들 중에서 $() 축약어를 사용하는 라이브러리입니다. 나는 당신이 단지 실제 라이브러리와 다른 뭔가가있는 고유 한 javascript'prototype' 속성을 사용하고 있다고 믿는다. –

+1

[duplicate of getElementsByClassName이 왜 나에게 적합하지 않습니까? 그것은 무엇을 반환합니까?] (http://stackoverflow.com/questions/10693845/why-getelementsbyclassname-does-not-work-for-me-what-does-it-return) –

+0

하지만 사용하면 말해 줄 수 있습니까? document.getElementsByClassName ('clck'); 이 대신 작동하지 않는 document.getElementById ('clck'); 그것의 일. – Tushky

답변

0

getElementsByClassName은 배열과 같은 객체를 반환합니다. 여기 체크 아웃 : getElementsByClassName

"Returns an array-like object of all child elements which have all of the given class names."

opnpopup 클래스 clck 모든 요소를 ​​포함하는 배열입니다. 배열의 이벤트는 바인딩 할 수 없습니다.

window.onload = function() { 
    var popup = new Popup(); 

    var opnpopup = document.getElementsByClassName('clck'); 

    for (index = 0; index < opnpopup.length; index++) 
     opnpopup[ index ].addEventListener('click', function() { 
     popup.openPopup(); 
     }); 

    var cnclpopup = document.getElementById('cancel'); 
    cnclpopup.addEventListener('click', function() { 
     popup.closePopup(); 
    }); 
} 

이 코드는 작동하므로이 배열의 모든 요소에 click 이벤트를 바인딩해야합니다.

+0

솔루션을 제공해 주셔서 감사합니다. 하지만 지금은 팝업이 표시되는 일을 쓰지 만 취소 버튼을 클릭하면 팝업이 닫히지 않습니다. – Tushky

+0

개발자 콘솔에 오류가 있습니까? – TheFrozenOne

+0

예 TypeError : opnpopup [index] .addEventListener는 함수가 아닙니다. – Tushky