2013-07-15 72 views
-1

我使用PHP curl發送數據到監聽端口並在屏幕上輸出數據,並且效果很好。 這是我發送的數據:jQuery on()無法動態添加事件

$arr = array("message" => "<u>".$abc."</u> at <u>".$currentDate."</u> || <a href=#>Call</a> || <a href=#>SMS</a> || <u class='caller'>N/A</u>"); 
$msgString = json_encode($arr); 
$ch = curl_init('http://localhost:8123/message'); 
curl_setopt($ch, 
      CURLOPT_CUSTOMREQUEST, 
      "POST"); 
curl_setopt($ch, 
      CURLOPT_POSTFIELDS, 
      $msgString);               
curl_setopt($ch, 
      CURLOPT_RETURNTRANSFER, 
      true);                
curl_setopt($ch, 
      CURLOPT_HTTPHEADER, 
      array('Content-Type:application/json', 
        'Content-Length:' . strlen($msgString))); 
$result = curl_exec($ch); 

這是完美的工作。然後我使用Chrome觀看元素。所有元素都可以。 enter image description here 接下來我使用jQuery來綁定它們的點擊功能,但我無法觸發它們。

//alert("123"); 
$('.caller').on("click", function(){ 
    console.log("11"); 
}); 

PS:代碼位於外部js文件中,我在主文件中正確包含了jquery庫。我使用警報來測試,它的工作原理。
我認爲問題是js代碼。我不知道爲什麼我不能觸發點擊事件。有人能告訴我爲什麼嗎?謝謝!

+1

你正在使用就像一個正常的點擊,你應該閱讀API的事件委派參數 – Spokey

回答

1

嘗試使用Direct and delegated events

$(document).on("click", '.caller', function(){ 
    console.log("11"); 
}); 

更好的選擇將是.caller你不動態更新的父元素的傳球選擇。

0

試試這個

jQuery(document).on("click",".caller",function() { 
console.log("11") 
}); 
0

你在哪裏位於該附加的處理功能:?

$('.caller').on("click", function(){ 
    console.log("11"); 
}); 

如果這就是所謂的$(document).ready或同等那麼它將只重視.caller元素那些已經被創建 - 它也不會附着在未來創建的元素。爲此,每次將新的.caller元素添加到DOM時,都需要再次調用該函數。

+1

或更好的,使用委託 –

+0

是啊,或者說!大聲笑 – Katstevens