【问题标题】:FireFox - attach event to dynamically added function?FireFox - 将事件附加到动态添加的功能?
【发布时间】:2017-09-12 19:02:25
【问题描述】:

我需要动态地将函数附加到 div 并传递事件。

它可以在 Chrome / IE 中运行,但不能在 FireFox 中运行。

我在 FireFox 控制台中收到以下错误:ReferenceError: event is not defined

如何解决?

代码笔: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>

【问题讨论】:

  • 这与动态元素无关,只是因为Firefox不支持全局事件对象而发生。

标签: javascript jquery html css firefox


【解决方案1】:

你试过了吗:

div.on("click",function(e) {Test(e);});

【讨论】:

    【解决方案2】:

    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>

    就是这样

    【讨论】:

    • 添加了一个 stack-sn-p
    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多