firefox js如何传递event

int32位 posted @ Aug 02, 2013 01:37:02 PM in 前端开发 , 2080 阅读
转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!

对于IE和chrome, 貌似window.event是个全局变量, 但对于firefox, 则不是全局的, 因此我们在定义Onclick函数需要传递参数时,需要把event传入,并且只能是第一个参数:

document.getElementById("button").onClick = function(e) {

alert(e);

}

然而我们写成这样该如何传递参数呢?

<button Onclick="foo();">按钮</button>

这就没法传入事件参数了, 因此需要自己写一个getEvent函数:

function getEvent()
{
	if (document.all)
		return window.event;
	func = getEvent.caller;
	while (func != null) {
		var arg0 = func.arguments[0];
		if (arg0) {

			if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation))
				return arg0;
		}
		func = func.caller;
	}
	return null;
}

然后传递时这样:

<button Onclick="foo(getEvent());">按钮</button>
转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!
  • 无匹配
  • 无匹配
Avatar_small
依云 说:
2013年8月02日 16:42

不一般写 onclick="foo(event || e);" 么?

Avatar_small
krystism 说:
2013年8月05日 13:27

@依云: firefox可以么? 我没有尝试过。

Avatar_small
krystism 说:
2013年8月05日 14:41

@依云: 刚试了下, 确实可以。

Avatar_small
λ 说:
2013年8月06日 02:20

@krystism: 应该用旧版的浏览器来测试吧,现在都什么年代了……
另外,依云说的 foo(event || e) 应该改为 foo(window.event) ,后面的 e 不是什么浏览器默认的全局变量,用 window.event 比直接用 event 好。

Avatar_small
依云 说:
2013年8月06日 10:25

@λ: 其实那个我也不知道什么原理啦 -_-|||
window.event 不是 IE 自己的特性么,火狐也支持了?
反正我已经 N 年没用过 onxxx 属性啦=w=

Avatar_small
λ 说:
2013年8月06日 20:49

@依云: 各大浏览器都支持了 http://help.dottoro.com/ljogqtqm.php
window.event 会同步当前发生的事件 object ,除了方便这类 onXXX 的写法之外貌似没有别的用处了……
现在的网页结构越来越模块化了,尤其是为了提高浏览安全性越来越不需要 onclick ,<script>xxx</script> 之类的 inline-script 和 style="xxx" 那些 inline-stylesheet 了~

Avatar_small
λ 说:
2013年8月06日 20:54

@依云: window 这个特殊的全局变量无法被全局覆盖。

Convert HEIC to PDF 说:
2021年11月26日 21:13

These are very simple and easier processes to get the PDF created from any of the HEIC image files.HEIC format is a much unknown format for other devices except the iOS devices, so any picture or document that has been captured in an iOS device cannot be shared with an Android or Windows device. Convert HEIC to PDF in Mac The file will be shared in HEIC format which is not supported and thus Convert HEIC to PDF in Mac is quite necessary before sharing. To Convert HEIC to PDF or JPEG files, the individual has to use their specific tools as PDF element or any such. To cover the HEAD into a JPEG file, it is more convenient to visit the online converting tool and select the format as JPEG which is quicker than getting a specific tool installed.

seo service london 说:
2024年2月21日 22:51

I really enjoy reading and also appreciate your work


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter