2013-09-28 150 views
0

爲了演示我的問題,我寫了這段代碼。Javascript事件發射兩次

main.php

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

子acc.php

<script> 
fx1(); 
</script> 

現在的問題是,當我點擊 「.elem」 按鈕,會出現警告2時間,即事件被激發兩次,我怎麼能防止這種情況。使用jquerymobile作爲前端框架。

+0

如何往往是FX1稱爲()。因爲任何時候你稱它爲.elem的一個事件監聽器都被註冊了 – Bernhard

+1

你碰巧有兩個類elem的嵌套元素嗎?還是你在任何地方再次調用fx()? – bfavaretto

+0

我試了一下代碼,它只發生一次。 – desbest

回答

2

嘗試定義事件偵聽器的方式和不調用FX1()了:

<body> 
//some html 

//some html again 
include sub-acc.php 

<script> 

    $(document).on("click", ".elem", function(event){ 
     alert("hello"); 
    }); 
</script> 
</body> 
+0

爲什麼要改變任何東西? –

+0

'.ready()'不應該用在JQM中。 – Omar