单击事件不能处理新的html with append,甚至使用on

时间:2014-08-18 10:39:05

标签: javascript jquery html

您好我正在使用Ajax中的beforesend创建该元素的新元素和子元素。

稍后我想显示子元素,如果我点击它的父...

$('#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

2 个答案:

答案 0 :(得分:0)

尝试在此背景下使用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);
});

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

答案 1 :(得分:0)

这不是代表的方式,比如说贝娄

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