0

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

我的代码是:

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

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

ajax 查询后的页面将是:

<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,这确实代码没用。

请帮帮我。

4

3 回答 3

0

这应该适合你:

$('#response').on('click', "#link_test", function(){
    alert("You Clicked Me");
});
于 2013-10-19T20:07:24.637 回答
0

事件委托:

$("#reponse").on("click", "#link_test", function(){
于 2013-10-19T20:07:31.623 回答
0

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

当许多元素必须触发相同的例程时,这是一个不错的选择,如果它们中的一些可能在未来通过 AJAX 添加到 DOM 中(这使页面不必附加许多事件处理程序)

委托语法

// Event delegation
$( "#firstCommonAncestorThatStillInThePage").on("click", 'a', function() {
    if($(this).is('#link_test')){
        alert( $( this ).text() );
    }
});
于 2013-10-19T20:08:15.297 回答