Javascript 事件触发两次

Javascript event firing two times

本文关键字:两次 事件 Javascript      更新时间:2023-09-26

为了演示我的问题,我编写了这段代码。

主.php

<body>
//some html
<script>
function fx1(){
   $(".elem").click(function(){
       alert("hello");
   })
}
</script>
//some html again
include sub-acc.php
</body>

子会计.php

<script>
 fx1();
</script>

现在的问题是,当我单击".elem"按钮时,警报出现两次,即事件被触发两次,我该如何防止这种情况。使用 jquerymobile 作为前端框架。

尝试以这种方式定义事件侦听器,不再调用 fx1():

<body>
//some html
//some html again
include sub-acc.php
<script>
    $(document).on("click", ".elem", function(event){
       alert("hello");
    }); 
</script>
</body>