javascript - 跨浏览器事件处理和 jquery 支持

标签 javascript jquery cross-browser jquery-events

刚刚阅读 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/

相关文章:

javascript - jQuery通过间隔、超时实现自动 slider

Javascript 函数被调用太多次

javascript - Handlebars - Access Navigator

javascript - 打开对话框窗口时更改 Css 样式

html文件上传表单

javascript - Kango 浏览器扩展开发中鼠标悬停事件弹出

javascript - 最初隐藏 iframe 时,Vimeo Javascript API 不起作用

javascript - 如何检查当前浏览器选项卡的 url 是否已更改?

javascript - 在 .content div 之间导航

javascript - 如何从 JavaScript 数组值中找到所有长度的所有排列?