2013-07-15 71 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