event.currentTarget in IE6

前端 未结 2 1574
情书的邮戳
情书的邮戳 2021-01-22 13:32

I\'ve got an event handler that I\'m attaching to an element to catch a bubbled click event. I need a reliable way of obtaining the element that caught<

相关标签:
2条回答
  • 2021-01-22 13:53

    Update: attachEvent really seems to create a problem here. From quirksmode.org:

    In the following cases this refers to the window:

    element.onclick = function () {doSomething()}
    element.attachEvent('onclick',doSomething)
    <element onclick="doSomething()">
    

    Note the presence of attachEvent(). The main drawback of the Microsoft event registration model is that attachEvent() creates a reference to the function and does not copy it. Therefore it is sometimes impossible to know which HTML currently handles the event.

    The only way how you could solve this seems to be by creating a wrapper, something like:

    var addListener = (function() {
        if(document.attachEvent) {
            return function(element, event, handler) {
                element.attachEvent('on' + event, function() {
                    var event = window.event;
                    event.currentTarget = element;
                    event.target = event.srcElement;
                    handler.call(element, event);
                });
            };
         }
         else {
            return function(element, event, handler) {
                element.addEventListener(event, handler, false);
            };
         }
    }());
    

    Then this would refer to the element, as would event.currentTarget and you'd pass event as first argument.

    Usage:

    addListener(element, 'click', function(e) {
        // this refers to element
        // e.currentTarget refers to element
        // e.target refers to the element that triggered the event
    }); 
    

    Old answer: (which works for inline and traditional event handlers, as well as addEventListener (but not attachEvent))

    Inside the event handler, this refers to the element the event handler is attached to.

    0 讨论(0)
  • 2021-01-22 14:07

    According to this article IE simply has no equivalent to currentTarget. Therefore, if you can't find a way to bind the events such that you get the correct element in target/srcElement, you could try adding a class to the element that you want to catch the event and traversing the DOM tree up to this element.

    <div class="eventCatcher">
        <div id="eventTrigger>More HTML</div>
    </div>
    
    <script>
        function catchEvent(event)
        {
            event = event || window.event;
            target = event.target || event.srcElement;
    
            while (!target.getAttribute('class').indexOf('eventCatcher') >= 0)
                target = target.parentElement;
        }
    </script>
    
    0 讨论(0)
提交回复
热议问题