javascript - 将事件绑定(bind)到动态生成的表单

标签 javascript jquery ajax forms

我有 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/

相关文章:

javascript - Facebook评论滚动

javascript - JSON.parse 仅在部署在 pythonanywhere 上时返回语法错误

javascript - 给定一个字符串,如何使用 JQuery 向其添加类?

javascript - dotenv 和 nodejs 未定义 process.env 变量

javascript - 使用 setDate 时日期对象与预期不符

javascript - IE8 返回 NaN

jquery - asp.net MVC 3 分页哪个最好用

javascript - Ajax onSuccess 回调,但无法控制 ajax 调用

javascript - Ajax 触发实时和动态表单

javascript - Jquery 和 Vue,.html() 不起作用