onclick处理程序事件

onclick处理程序事件

本文介绍了IE8 onclick处理程序事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了quirksmode.org上的大部分相关文章,但我仍然不确定这个:

I've read most of the relevant articles in quirksmode.org but still I'm not sure about this one:

让我的应用与IE8兼容(好玩)有趣的是)我在尝试将onclick事件设置为链接时遇到此问题:

Making my app compatible with IE8 (fun fun fun) I encounter this issue when trying to set an onclick event to a link:

function myClickHandler(event)
{
    alert(event);
}

var link = document.getElementById("myLink");
link.onclick = myClickHandler; //first option

相反:

function myClickHandler(event)
{
    alert(event);
}

var link = document.getElementById("myLink");
link.onclick = function() {
   myClickHandler(event); //second option
}

使用第一个选项,myClickHandler提醒未定义。使用第二个选项提醒 [object Event] 这让我相信事件对象没有被第一个选项传递给处理程序。为什么在IE8上如此?

Using the first option, myClickHandler alerts undefined. Using the second option alerts [object Event] which makes me believe that the event object isn't passed by the first option to the handler. Why is this so on IE8?

注意:不想使用attachEvent,因为我想在执行期间覆盖单个侦听器并且 onclick 似乎很适合。

Note: Don't want to use attachEvent as I want to override a single listener during execution and onclick seems to fit here fine.

推荐答案

是的,事件对象不作为参数传递给DOM0 IE中的样式事件处理程序< = 8.您需要从 window.event 获取它。如果添加一个名为 event 的参数,则在IE< = 8中,这将是 undefined 并引用<$ c事件处理程序中的$ c> event 将解析为undefined参数而不是 window.event 。我通常使用 window.event 在代码中明确显示:

Yes, the event object is not passed as a parameter to DOM0-style event handlers in IE <= 8. You need to get it from window.event instead. If you add a parameter called event, in IE <= 8 this will be undefined and references to event within the event handler will resolve to the undefined parameter rather than window.event. I usually use window.event to make this explicit in the code:

link.onclick = function(evt) {
   evt = evt || window.event;
}

这篇关于IE8 onclick处理程序事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:21