我有 2 个函数,第一个函数调用表单,第二个函数通过 ajax 提交该表单。但是我无法将提交事件绑定(bind)到新创建的表单,为什么会这样?
获取表格
$("#discount").click(function(){
$.ajax({url:"index.php?module=products&view=addajax",success:function(result){
$(".forma").html(result);
}});
});
通过ajax提交此表单
$('#my_form').on('submit', (function(evnt){
evnt.preventDefault(); //Avoid that the event 'submit' continues with its normal execution, so that, we avoid to reload the whole page
data = $("form#my_form").serialize();
$.post('index.php/products/adds',
$("form#my_form").serialize(), //Serialize all the content of our form to URL format
function (data) {
$('div#sending_form').prepend(data); //Add the AJAX response to some div that is going to show the message
})
}));
最佳答案
您无法直接绑定(bind)到当前不存在的元素的事件。为此,您需要使用 delegated events
例如:
$('.forma').on('submit', 'form', function(evnt){
//submit
});
关于javascript - 将事件绑定(bind)到动态生成的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23399245/