刚刚阅读 ppk 的网站,IE 的注册事件机制不会将 this
对象设置为被单击的实际元素。相反,它指的是全局窗口对象。 below引用自他的网站:
But when you use the Microsoft event registration model the this keyword doesn’t refer to the HTML element. Combined with the lack of a currentTarget–like property in the Microsoft model, this means that if you do
element1.attachEvent('onclick',doSomething) element2.attachEvent('onclick',doSomething)
you cannot know which HTML element currently handles the event. This is the most serious problem with the Microsoft event registration model and for me it’s reason enough never to use it, not even in IE/Win only applications.
jQuery 正确地处理了这个问题!我的意思是如果我们做类似的事情:
$(element).click(function(){...});
this
指的是问题中的元素。 jQuery 如何为 IE 浏览器处理这个问题?它的等效 js 代码是什么?
最佳答案
使用call
方法,你可以在任何函数中设置this
的值:
var element = document.getElementById('testy'),
someFunction = function () {
alert(this.id);
};
someFunction.call(element); // alerts "testy"
这就是几乎每个库修复 IE 愚蠢的“这个”错误的方法:通过向您传入的监听器添加包装器,以便您的监听器实际上被调用
。
关于javascript - 跨浏览器事件处理和 jquery 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940964/