将事件绑定到动态生成的表单

时间:2014-04-30 22:36:52

标签: javascript jquery ajax forms

我有2个函数,第一个调用一个表单,第二个通过ajax提交表单。 Hovewer我无法将提交事件绑定到新创建的表单,为什么会这样?

获取表格

$("#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
    }) 
}));

3 个答案:

答案 0 :(得分:1)

您无法直接绑定到当前不存在的元素的事件。为此,您需要使用delegated events

例如:

$('.forma').on('submit', 'form', function(evnt){
    //submit
});

答案 1 :(得分:1)

尝试使用on()语法:

$( "body" ).on( "submit", "#my_form", function() { 
    // your code
});

答案 2 :(得分:1)

如果它已动态添加到页面中,那么您将无法将click事件绑定到该页面。而是使用on()将事件绑定到从页面上的现有元素新创建的任何子项(即DOM加载时)

您的新on()点击事件将如下所示:

$('.forma').on('click','form', function(e) {
  // logic here
});

.forma是加载DOM时存在的元素的类。

另一个例子:

如果您已使用jQuery将<li>添加到<ul>,那么您可以将click事件分配给每个<li>内的超链接,如下所示:

$('ul.testClass').on('click','li a', function(e) {
    e.preventDefault();
    // custom hyperlink behaviour here
});

此处有关on()的更多信息:https://api.jquery.com/on/

相关问题