如何从ajax结果将click事件绑定到按钮

时间:2018-04-20 14:41:22

标签: jquery ajax

所以我有Button_1,当点击时,它会使用ajax请求一个新的button_2。两个按钮在我的jquery(文档).ready上都有click事件,但是当按钮2添加到页面时,它上面没有jquery事件。这可能吗?

这是我在页面加载时的代码:

jQuery(document).ready(function($){

$('#button_1').click(function(e){
    e.preventDefault();
    var id = $(this).data('id');

    $.ajax({
        type: 'POST',
        url: 'get_button_2.php',
        data: 'id='+id,
        dataType: 'html'
    })
    .done(function(response){
        $('#button-container').html('');
        $('#button_1').remove(); // remove button 1
        $('#button-container').html(response).show('500');
    })
    .fail(function(){
        $('#button-container').html('Something went wrong');
    });

});


$('#button_2').click(function(e){
    e.preventDefault();
    alert ('Thank You!');
});

});

1 个答案:

答案 0 :(得分:3)

您必须在 DOM 上创建活动。

$(document).on('click', '#button_2', function(e){
    e.preventDefault();
    alert ('Thank You!');
});


参考: http://api.jquery.com/on/

相关问题