跨浏览器事件处理和jquery支持 [英] cross browser event handling and jquery support
问题描述
只是阅读ppk的网站,IE的注册事件的机制不会将这个
对象设置为点击的实际元素。相反,它引用全局窗口对象。以下 的引述来自他的网站:
但是当您使用Microsoft事件
注册模型时,this关键字
不会引用HTML元素。
结合在
Microsoft模型中缺少
currentTarget样属性,这意味着如果
你做element1.attachEvent('onclick',doSomething)
element2.attachEvent('onclick',doSomething)
您不能知道
当前处理事件的HTML元素。这是
最严重的问题与
微软事件注册模型和
对我来说,足够的原因,不能使用
它,甚至在IE / Win只有
应用程序。
jQuery正确处理这个问题!我的意思是,如果我们做的像:
$(element).click(function(){...});
此
是指问题中的元素。 jQuery如何处理这个IE浏览器? c 调用
var element = document.getElementById('testy'),
someFunction = function(){
alert(this.id);
};
someFunction.call(element); //警告testy
这是几乎每个库修复IE的愚蠢的这个错误:by向您传递的侦听器添加一个包装器,以便您的侦听器实际上调用
。
Just read of ppk's web site that IE's mechanism of registering events does not set the this
object to the actual element that was clicked. Instead it refers to the global window object. The below is quoted from his site:
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 handles this properly! I mean if we do something like:
$(element).click(function(){...});
this
refers to the element in the question. How does jquery handle this for IE browsers? What would be the equivalent js code for it?
Using the call
method, you can set the value of this
in any function:
var element = document.getElementById('testy'),
someFunction = function () {
alert(this.id);
};
someFunction.call(element); // alerts "testy"
This is how almost every library fixes IE's stupid "this" mistake: by adding a wrapper to the listener that you pass in, so that your listener is actually called
.
这篇关于跨浏览器事件处理和jquery支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!