阅读AJAX返回的数据

问题描述:

我正在做一个填充我的html页面的ajax请求。我在ajax响应页面上有一个锚标记。我想通过它的id访问html锚标签并显示一个alery。阅读AJAX返回的数据

我的代码是:

<div id="response"> 
</div> 

$.post("destination.php",function(data){ 
$("#response").html(data); 
}); 

阿贾克斯查询后,页面将是:

<div id="response"> 
<a href="some_link.php" id="link_test">Click Me</a> 
</div> 

,现在我想使用jQuery访问此数据:

$("#link_test").on('click',function(){ 
alert("You Clicked Me"); 
}); 

但我无法在我的页面上执行此操作,因为它是ajax请求,并且在ajax请求之后不会刷新ID。所以浏览器不能识别这个id,这个代码确实没用。

请帮我一把。

这应该为你工作:

$('#response').on('click', "#link_test", function(){ 
    alert("You Clicked Me"); 
}); 

事件委托:

$("#reponse").on("click", "#link_test", function(){ 

您可以使用事件委托这意味着你必须将事件侦听器附加到这些按钮的共同祖先。

这是一个很好的选择,当许多元素必须触发相同的例程,甚至更多,如果他们中的一些可能通过AJAX添加到未来的DOM(这使得页面不得不连接到许多事件处理程序)

代表团语法

// Event delegation 
$("#firstCommonAncestorThatStillInThePage").on("click", 'a', function() { 
    if($(this).is('#link_test')){ 
     alert($(this).text()); 
    } 
});