FireFox - 将事件附加到动态添加的函数?
2017-09-12
75
我需要动态地将一个函数附加到 div 并传递事件。
它在 Chrome / IE 中可以工作,但不能在 FireFox 中工作。
我在 FireFox 控制台中收到以下错误: ReferenceError:未定义事件
如何解决这个问题?
CodePen: https://codepen.io/dsomekh/pen/YrKmaR
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.example{
cursor:pointer;
border:1px solid black;
text-align:center;
}
</style>
<script>
window.onload = function() {
var div = $( ".example" );
div.click(function() {Test(event);});
}
function Test (event)
{
alert(event);
}
</script>
<html>
<div class="example">When clicking on this div, you should get an alert with the event details. This does not work in FireFox.</div>
</html>
2个回答
您是否尝试过:
div.on("click",function(e) {Test(e);});
somosluz
2017-09-12
Firefox 不支持全局事件对象,它需要将事件作为参数传递
window.onload = function() {
var div = $( ".example" );
div.click(function(event) { // needs to be here
Test(event);
});
}
function Test (event){
alert(event);
}
您也可以只引用该函数,然后执行
div.click(Test);
因此您将得到
$(function() {
$(".example").on('click', Test)
});
function Test (event) {
console.log(event);
}
.example{
cursor:pointer;
border:1px solid black;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example">When clicking on this div, you should get an alert with the event details. This does not work in FireFox.</div>
就是这样
adeneo
2017-09-12