如何从ajax结果将click事件绑定到按钮 [英] How to bind click event to button from ajax result
本文介绍了如何从ajax结果将click事件绑定到按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有Button_1,当点击时,它会使用ajax请求一个新的button_2。两个按钮在我的jquery(文档).ready上都有click事件,但是当按钮2添加到页面时,它上面没有jquery事件。这可能吗?
So I have Button_1 that when click, it will request a new button_2 using ajax. Both button has click event on my jquery(document).ready but when the button 2 added to the page, it doens't have jquery event on it. Is that possible?
这是我在页面加载时的代码:
Here is my code on page load:
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!');
});
});
推荐答案
您必须在 DOM上创建活动。
You have to create the event on DOM.
$(document).on('click', '#button_2', function(e){
e.preventDefault();
alert ('Thank You!');
});
REF: http://api.jquery.com/on/
这篇关于如何从ajax结果将click事件绑定到按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文