开发者

Cross browser event handling and jquery support

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 windo开发者_Python百科w 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜