繁体   English   中英

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

[英]Bind event to dynamically generated form

我有2个函数,第一个函数调用表单,第二个函数通过ajax提交该表单。 但是我不能将Submit事件绑定到新创建的表单,为什么会这样呢?

取得表格

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

您不能直接绑定到当前不存在的元素的事件。 为此,您需要使用委托事件

例如:

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

尝试通过以下语法使用on()

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

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

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

$('.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()更多信息on()访问: https//api.jquery.com/on/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM