动态内容上的jQuery滑块,使用bind()无法正常工作

时间:2015-02-24 10:24:35

标签: jquery

我有以下代码,我试图在单击时向表中添加一行,在这个动态生成的行中我想要一个jQuery UI滑块。出现该行但滑块未添加到div ...

我刚刚注意到,当我单击滑块出现的区域时,我认为这与绑定点击事件有关,如何将其绑定到表格单元格区域中没有单击?

$('.add_task').unbind().bind('click', function(){

    $('.add_cancel_wrap').html('<button class="cancel_add_task btn btn-primary">Cancel</button>');

    $('.cancel_add_task').unbind().bind('click', function(){
        window.location = window.location.href;
    });

    var user_id = $(this).data('user-id');

    var $html = $('<td></td><td><input class="description" type="text" value="" placeholder="Description" /></td><td><div class="time-slide"></div><div id="slide-range-area"></div></td><td></td><td><a href="" class="save_new_task" title="Save"><span class="glyphicon glyphicon-floppy-disk"></span></a></td><td><input class="time" /></td>');

    $html.bind('click', function(){

        $(function() {
            $(".time-slide").slider({
                range: false,
                min: 0,
                max: 480,
                step: 10,
                slide: function(e, ui) {
                    var hours = Math.floor(ui.value / 60);
                    var minutes = ui.value - (hours * 60);

                    if(hours.length == 1) hours = '0' + hours;
                    if(minutes.length == 1) minutes = '0' + minutes;

                    $('#slide-range-area').html(hours+' Hrs '+minutes+' mins');
                }

            });
        });

    });

    $('<tr></tr>').appendTo('#tasks_table').hide().append($html).fadeIn('slow');

});

感谢

1 个答案:

答案 0 :(得分:0)

没有必要使用点击处理程序...你可以在创建dom元素后初始化插件,所以

$('.add_cancel_wrap').on('click', '.cancel_add_task', function () {
    window.location = window.location.href;
});

$('.add_task').unbind().bind('click', function () {
    $('.add_cancel_wrap').html('<button class="cancel_add_task btn btn-primary">Cancel</button>');

    var user_id = $(this).data('user-id');

    var $html = $('<tr><td></td><td><input class="description" type="text" value="" placeholder="Description" /></td><td><div class="time-slide"></div><div class="slide-range-area"></div></td><td></td><td><a href="" class="save_new_task" title="Save"><span class="glyphicon glyphicon-floppy-disk"></span></a></td><td><input class="time" /></td></tr>');

    $html.find(".time-slide").slider({
        range: false,
        min: 0,
        max: 480,
        step: 10,
        slide: function (e, ui) {
            var hours = Math.floor(ui.value / 60);
            var minutes = ui.value - (hours * 60);

            if (hours.length == 1) hours = '0' + hours;
            if (minutes.length == 1) minutes = '0' + minutes;

            $html.find('.slide-range-area').html(hours + ' Hrs ' + minutes + ' mins');
        }

    });
    $html.hide().appendTo('#tasks_table').append().fadeIn('slow');
});

还有与add_cancel_wrap

的委派事件处理程序相关的细微更改