60

Internet Explorer 9의 요소 개체와 동일한 기능은 무엇입니까?Internet Explorer의 addEventListener

if (!Element.prototype.addEventListener) { 
    Element.prototype.addEventListener = function() { .. } 
} 

Internet Explorer에서 어떻게 작동합니까?

기능이 addEventListener인데 모르겠다면 설명하십시오.

도움을 주시면 감사하겠습니다. 문제를 완전히 다른 방식으로 해결할 것을 제안하십시오.

+0

브라우저가 DOM 객체에 대한 프로토 타입 상속 체계를 구현하는지 여부는 W3C [EventTarget 인터페이스] (http://www.w3.org/TR/DOM-Level-2-Events/events)를 지원하는지 여부와 관련이 없습니다. .html # Events-EventTarget-addEventListener). if (element.addEventListener) {/ * supported * /} else {/ * not supported * /}'는 모든 브라우저에서 유효하며 구현과 독립적입니다. – RobG

답변

131

addEventListener은 이벤트 처리기를 연결하는 데 사용할 적절한 DOM 방법입니다.

Internet Explorer (버전 8까지)는 attachEvent 대체 방법을 사용했습니다.

Internet Explorer 9에서는 적절한 addEventListener 메서드를 지원합니다.

다음은 브라우저 간 addEvent 함수를 작성하려는 시도입니다.

function addEvent(evnt, elem, func) { 
    if (elem.addEventListener) // W3C DOM 
     elem.addEventListener(evnt,func,false); 
    else if (elem.attachEvent) { // IE DOM 
     elem.attachEvent("on"+evnt, func); 
    } 
    else { // No much to do 
     elem[evnt] = func; 
    } 
} 
+18

마지막 조건은 "+"에 ""을 포함해야합니다. –

+69

IE9 및 addEventListener의 경우 HTML5 pcunite

+1

@pcunite가 필요합니다. 그 주석을 더 많이 투표 할 수 있기를 바랍니다. 매우 중요한 점 – Okeydoke

1

addEventListener은 버전 9부터 지원됩니다. 이전 버전의 경우 다소 비슷한 attachEvent 기능을 사용합니다.

2

Delan이 말했듯이 최신 버전에는 addEventListener를, 이전 버전에는 attachEvent를 사용하려고합니다.

이벤트 리스너에 대한 자세한 내용은 MDN입니다. (청중에 'this'값이있는 몇 가지주의 사항이 있습니다).

jQuery과 같은 프레임 워크를 사용하여 이벤트 처리를 추상화 할 수도 있습니다.

$("#someelementid").bind("click", function (event) { 
    // etc... $(this) is whetver caused the event 
}); 
16

존 레식, jQuery를의 저자, ​​호환성 문제를 회피 addEventremoveEvent의 크로스 브라우저 구현의 자신의 버전을 제출 IE의 부적절하거나 addEventListener 존재.

function addEvent(obj, type, fn) { 
    if (obj.attachEvent) { 
    obj['e'+type+fn] = fn; 
    obj[type+fn] = function(){obj['e'+type+fn](window.event);} 
    obj.attachEvent('on'+type, obj[type+fn]); 
    } else 
    obj.addEventListener(type, fn, false); 
} 
function removeEvent(obj, type, fn) { 
    if (obj.detachEvent) { 
    obj.detachEvent('on'+type, obj[type+fn]); 
    obj[type+fn] = null; 
    } else 
    obj.removeEventListener(type, fn, false); 
} 

자료 : I는이 솔루션을 사용하고 IE8에서 이상 작동하고있어 http://ejohn.org/projects/flexible-javascript-events/

+0

이 코드는 이벤트 리스너를 추가하는 것 외에도 콜백 fn을 obj에 바인드하려고 시도하지만, JS를 사용하는 모든 사람이 이미 'this'에 대해 알고 있어야하므로 중복됩니다. –

+3

John Resig를 ** jQuery **의 저자로 소개했다면 더 많은 표를 얻었을 것입니다. –

+0

좋은 점, 업데이트 – jchook

13

.

if (typeof Element.prototype.addEventListener === 'undefined') { 
    Element.prototype.addEventListener = function (e, callback) { 
     e = 'on' + e; 
     return this.attachEvent(e, callback); 
    }; 
    } 

: 그리고

<button class="click-me">Say Hello</button> 

<script> 
    document.querySelectorAll('.click-me')[0].addEventListener('click', function() { 
    console.log('Hello'); 
    }); 
</script> 

이 IE8과 크롬, 파이어 폭스 등 모두 작동합니다

+0

요소에 문제가 있습니다 (형식이 정의되지 않음) – zchpit

+0

문서 형식 버전을 확인하십시오.이 형식은 html5 doctype이어야합니다. – Teobaldo

1

편집

가 나는의 EventListener 인터페이스와 IE8을 모방 코드 조각을 썼다도 일반 개체에 대한 호출입니다 :이 에뮬레이션을하여 addEventListener 또는 방법입니다

https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

OLD 답변 attachEvent를 지원하지 않는 브라우저에서
희망 하시겠습니까?

(function (w,d) { // 
    var 
     nc = "", nu = "", nr = "", t, 
     a = "addEventListener", 
     n = a in w, 
     c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","")), 
     u = n?(nu = "attach", "add"):(nu = "add","attach"), 
     r = n?(nr = "detach","remove"):(nr = "remove","detach") 
/* 
* the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener" 
*/ 
    function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture()) : capt ))}} 
    w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener] 
    w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener] 

})(window, document) 
1

여기에 아름 다운 코드를 좋아하는 사람들을 위해 뭔가를 사용할 수 있습니다.

function addEventListener(obj,evt,func){ 
    if ('addEventListener' in window){ 
     obj.addEventListener(evt,func, false); 
    } else if ('attachEvent' in window){//IE 
     obj.attachEvent('on'+evt,func); 
    } 
} 

뻔뻔스럽게도 Iframe-Resizer에서 도난당했습니다.

관련 문제