cross browser event handling and jquery support

2019-08-14 16:38发布

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?

1条回答
淡お忘
2楼-- · 2019-08-14 17:07

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.

查看更多
登录 后发表回答