简体   繁体   中英

Setting on click action for dynamically generated links

I have div of links that get dynamically generated. I am trying to set the on click action of the links but it is not working.

Code:

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

The links in the tags div are generated by the following code:

$("#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");
});

You can try it:

 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); 

This is because at the moment when you set the events, the link not exists. You should set the click event after the link exists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM