为动态生成的链接设置单击动作

Setting on click action for dynamically generated links

本文关键字:设置 单击 链接 动态      更新时间:2023-09-26

我有动态生成的链接div。我正在尝试设置链接的点击操作,但它不工作。

代码:

$('#tags').on('click', 'a', function(event) {
    event.preventDefault();
    $("#content").html("hello");
});

标签div中的链接由以下代码生成:

$("#alpha_menu li").each(function() {
    $("#alpha_menu li a").click(function(event) {
        event.preventDefault();
        $.post('tags_script.php', {id: $(this).text()}, function(data) {
            $("#tags").html(data);
        });
    });
});

try this (outside document ready):

$(document).on('click', '#tags a', function(event) {
    event.preventDefault();
    $("#content").html("hello");
});

你可以试试:

var attachLink = function(event){ 
    event.preventDefault();
    $.post('tags_script.php', {id: $(this).text()}, function(data) {
        $('#tags').off();
        $('#tags').html(data);
        $('#tags').on('click', 'a', attachLink);
        //console.log(attachLink);
    });
}
$('#tags').on('click', 'a', attachLink);

这是因为当您设置事件时,链接不存在。您应该在链接存在之后设置点击事件