Click() 在 IE 中有效,但在 Firefox 中无效 [英] Click() works in IE but not Firefox

查看:36
本文介绍了Click() 在 IE 中有效,但在 Firefox 中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码很简单,但只能在 IE 中运行,不能在 Firefox 中运行.

I have code which is trivial but only works in IE not Firefox.

$(document).ready(function(){
    $('li#first').click();
});

我也试过:

document.getElementById('first').click();

但这也行不通.

这是 IE 错误/功能还是其他浏览器不支持 click()?

Is this an IE bug/feature or is click() not supported in the other browsers?

回复评论:

  1. 有一个带有 ID 的元素首先,没有了.
  2. 单击列表元素可展开元素并将焦点移到 Google 地图元素上.
  3. 在 patrick 的响应中运行代码(向元素添加另一个点击事件)产生了一些有趣的行为.当运行 $('li#first').click() 时,只触发了新事件,但是用鼠标物理点击元素同时触发了(新的和原始的).
  1. There is a single element with ID first, no more.
  2. It is an onclick on the list element that expands the element and moves focus on a Google Map element.
  3. Running the code in patrick's response (adding another click event to the element) produced some interesting behaviour. When running $('li#first').click() only the new event fired, but physically clicking the element with the mouse fired both (new and original).

提前致谢.

推荐答案

Firefox 不支持 click().

Firefox does not support click().

运行 document.getElementById('first').click() 返回以下错误 click is not a function

Running document.getElementById('first').click() returns the following error click is not a function

所以我添加了一段代码来为每个元素添加 click() 功能.此代码是在一系列痛苦的谷歌搜索后找到的这个话题.

So I added a snippet of code to add click() functionality to every element. This code was found after a painful series of google searches resulting in this thread.

该代码段在下方,只需在页面上包含一次:

The snippet is below and needs to be included just once on the page:

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);
} 

这篇关于Click() 在 IE 中有效,但在 Firefox 中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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