简体   繁体   English

Javascript IE8无法从attachEvent获取“ this”

[英]Javascript IE8 not getting 'this' from attachEvent

This is a method of a larger class 这是大类的方法

myMethod.prototype.click=function(func){

 if (window.addEventListener) {
  this.selArray[i].addEventListener('click', func, false);
} else if (window.attachEvent) {
  this.selArray[i].attachEvent('onclick', func);
}


return this;

}

Which if I instigate passing this function.... 如果我鼓励传递此函数,则...。

myInstance.click(

    function () {
    alert(this.id)
    }
);

...alerts 'undefined' in IE 8 but returns the ID of the DOM object the click event is attached to in Firefox and Safari. ...会在IE 8中提示“未定义”,但会返回Firefox和Safari中click事件附加到的DOM对象的ID。

Right, attachEvent doesn't quite work the way addEventListener does. 是的, attachEventaddEventListener不太一样。 You can do this: 你可以这样做:

if (window.addEventListener) {
  this.selArray[i].addEventListener('click', func, false);
} else if (window.attachEvent) {
  this.selArray[i].attachEvent('onclick', func.bind(this.selArray[i]));
}

That uses Function#bind to ensure that this is the element on which you're hooking the event. Function#bind使用Function#bind来确保this是挂接事件的元素。 You have have to shim/polyfill Function#bind on older browsers (like IE8), search for "es5 shim" for options. 您必须在较旧的浏览器(如IE8)上执行Shim / polyfill Function#bind ,搜索“ es5 shim”以获取选项。

Or if you don't want to use Function#bind , use a closure over the call to click : 或者,如果您不想使用Function#bindclick在调用上使用闭包以click

myMethod.prototype.click=function(func){
    var elm = this.selArray[i];
    if (window.addEventListener) {
      elm.addEventListener('click', func, false);
    } else if (window.attachEvent) {
      elm.attachEvent('onclick', function(e) {
        return func.call(elm, e || window.event);
      });
    }

    return this;
}

Side note: Browsers that only supply attachEvent don't have preventDefault or stopPropagation on the event object, either. 旁注:仅提供attachEvent浏览stopPropagation在事件对象上也没有preventDefaultstopPropagation A thorough shim (such as that in jQuery or PrototypeJS or various other libraries) adds those. 彻底的填充(例如jQuery或PrototypeJS或其他各种库中的填充)会添加这些填充。 The equivalent of preventDefault is e.returnValue = false; 等效的preventDefaulte.returnValue = false; ; ; the equivalent of stopPropagation is e.cancelBubble = true; 相当于stopPropagatione.cancelBubble = true; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM