这是我遇到的问题的 MCVE。假设我有这个非常简单的测试页:
<html>
<header>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
function testMethod(e){
alert(e.target.id);
}
$(document).ready(function(){
$("#btn_test").on("click", testMethod, event);
});
</script>
</header>
<body>
<input type="button" id="btn_test" value="OK" />
</body>
</html>
您可以找到 jsfiddle here .
在 Chrome 或 IE 中,当我按下按钮时,id 将显示在消息框中。但在 Firefox 中,由于 window.event 未定义,我无法将 testMethod 绑定(bind)到按钮的 onclick 事件。
我知道如果我在内联编写它,我可以像这样传递事件:
onclick="testMethod(event)"
但是我如何在 Firefox 中将事件传递给我的函数而不用内联编写呢?
最佳答案
通常,当您使用 on
或 addEventListener
订阅事件时,事件对象会作为参数传递给回调。注册回调时,您永远不必显式传递它。所以这样做:
$("#btn_test").on("click", testMethod);
你的代码在 Firefox 上的问题是没有全局 event
属性,你会得到一个错误:
ReferenceError: event is not defined
并且您的事件订阅永远不会被注册。
关于javascript - 将事件对象传递给 firefox 中的触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44173332/