在jquery中,on methode无法正常工作
我有一个ajax post函数,从getcontact.php获取值,并附加到htmls中。当我使用on方法单击动态内容时,如果html被正确附加,则警报功能将不起作用。请帮帮我。 我的代码如下 jquery代码:在jquery中,on methode无法正常工作,jquery,Jquery,我有一个ajax post函数,从getcontact.php获取值,并附加到htmls中。当我使用on方法单击动态内容时,如果html被正确附加,则警报功能将不起作用。请帮帮我。 我的代码如下 jquery代码: $(document).ready(function(){ $(".val").click(function(){ value = $(this).attr('value'); $.post('../controller/getcontact.php', {
$(document).ready(function(){
$(".val").click(function(){
value = $(this).attr('value');
$.post('../controller/getcontact.php',
{ id : value , type : 1 },
function(data) {
alert(data);
$("#allUserDiv1").html(data);
}
);
});
$(".allUsers").on("click", function(){
alert("hai");
});
});
getcontact.php如下所示
<?php require_once("../model/regModel.php");
//for adding state and city
//type = 1 for state and type = 2 for city
error_reporting(0);
if(isset($_REQUEST['type'])) {
$type = $_REQUEST['type'];
$id = $_REQUEST['id'];
$service = new ServiceClass();
$result_array = array();
if($type == 1) { //select contact
$contact = $service->getContact($id);
while($result = mysql_fetch_array($contact)) {
$conid = $result['con_id'];
$conname = $result['con_name'];
$optionString .= "<li id=".$conid." class='allUsers' background-color:#CCCCCC;' >".$conname."</li>";
}
print_r($optionString);exit();
}
}
?>
正如您所提到的。allUsers是动态内容,您不能在创建元素之前简单地将其附加到事件处理程序上
选择1
选择2
在ajax成功回调中添加以下方法,这确保在创建元素后附加事件
$(".allUsers").on("click", function(){
alert("hai");
});
你的HTML在哪里?也不要发布与问题无关的代码。。。例如PHP代码。首先检查jquery版本,然后在下面尝试回答$allUserDiv1.onclick、.allUsers、函数{alerthai;};
$(".allUsers").on("click", function(){
alert("hai");
});