简体   繁体   English

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

[英]Setting on click action for dynamically generated links

I have div of links that get dynamically generated. 我有动态生成的链接的div。 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: 标签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");
});

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 链接存在后,您应该设置点击事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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