点击事件不工作的新HTML与追加,即使使用on

click event not working on new html with append , even using on

本文关键字:追加 on HTML 事件 工作      更新时间:2023-09-26

嗨,我正在创建一个新的元素和beforesend在Ajax元素的子元素。

之后我想显示子元素如果我点击它的父元素…

$('#submit-task').on('click', function() {
    // variable declarations etc
    jQuery.ajax({
        // other data
        beforeSend: function() {
            jQuery('#' + month + ' .month-tasks-design').append(
                '<div class="month-task" data-id="' + next_id + '" style="width:0%;background: ' + colour + ';"><div class="task-info">Name: ' + name + '<br />Design Hours: ' + design_hours + '<br />Description: ' + description + '<br /></div></div>');
            jQuery('#' + month + ' .month-tasks-dev').append(
                '<div class="month-task" data-id="' + next_id + '" style="width:0%;background: ' + colour + ';"><div class="task-info">Name: ' + name + '<br />Development Hours: ' + dev_hours + '<br />Description: ' + description + '<br /></div></div>');
            jQuery('.month-tasks-design div[data-id=' + next_id + ']').animate({ width: design_width + '%'}, 1000,  function() {});
            jQuery('.month-tasks-dev div[data-id=' + next_id + ']').animate({ width: dev_width + '%'}, 1000,  function() {});               

        },
        // other data
    }); 
});
$('.month-task').on('click', function(e) {
    if ( e.target !== this ) { return; }
    var task_info = $(this).find('.task-info');
    $(task_info).fadeIn(200);
});

然而,当我点击.month-task时什么也没发生,它确实工作,但与页面加载的html,只是不与新生成的html

尝试在此上下文中使用event-delegation

$(document).on('click','.month-task', function(e) {
    if ( e.target !== this ) { return; }
    var task_info = $(this).find('.task-info');
    $(task_info).fadeIn(200);
});

注意:在document的位置,您应该使用附加元素的静态父元素

这不是委派的方式,比如下面

$(document).on('click', '.month-task', function(e) {