为什么点击事件在Firefox中工作正常但不是IE [英] Why click event working fine in Firefox but not IE

查看:106
本文介绍了为什么点击事件在Firefox中工作正常但不是IE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的场景,点击事件在Firefox中运行正常但不是IE。让我们详细介绍一下。我有一个按钮,如下所示:

This is a simple scenario, the click event is working fine in Firefox but not IE. Let's go in the detail. I have a button which is like below:

<h:form id="theForm">
  <h:commandLink id="theButton" styleClass="button" action="#{theBean.doWork}"/>
</h:form>

当我尝试从JavaScript调用按钮的click事件时:

When I try to invoke the click event of the button from JavaScript like this:

document.getElementById('theForm:theButton').click();

根据这个主题,我需要将代码放在下面这样:

According to this thread, I am required to put the code below like this:

<script language="javascript" type="text/javascript">
  HTMLElement.prototype.click = function() {
    var evt = this.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    this.dispatchEvent(evt);
  }

但是当我在JavaScript中使用此代码时,它确实可以在Firefox中运行,但不再在IE中了。我可以知道如何在IE和Firefox上使用它?

But when I have this code in my JavaScript, it really work in Firefox, but not in IE anymore. May I know how can I make it work on both IE and Firefox?

推荐答案

尝试:

if(!HTMLElement){
var HTMLElement = Element;
}
HTMLElement.prototype.click = function() {
    var evt = this.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    this.dispatchEvent(evt);
}

这应该适用于IE> = 8,它使用元素在其他浏览器中提供相同的接口 HTMLElement

This should work for IE>=8, which uses Element to provide the same interface HTMLElement does in other browsers.

这篇关于为什么点击事件在Firefox中工作正常但不是IE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆