如何将提交事件添加到动态生成的表单?

Pra*_*een 0 jquery

以下是生成表单的PHP代码:form.php

 <?php
    echo '
    <form action="/wall/comment.php" method="post" id="submit-comment-form" name="'.$postid.'"> 
    <div class="write-comment-profile-pic">
    <img src= "'.$myprofilepic.'" width="30" height="30""/>
    </div>
    <div class="write-comment-textbox-wrap">
    <input type="text" class="textbox4" id="write-comment-textbox" value="Write a comment..." name="comment" style="width:65%;" />
    </div>
   </form>
   ';
   ?>
Run Code Online (Sandbox Code Playgroud)

得到form.php的Jquery代码

$('#images img').click(function() { 
$.get('form.php', function(data) {
$('#image-pop-up').html(data);
});
});
Run Code Online (Sandbox Code Playgroud)

这里是需要提交表单的jquery代码:

$('#image-pop-up').on('submit', '#submit-comment-form', function() { 
evt.preventDefault();       
});
Run Code Online (Sandbox Code Playgroud)

在index.html中,image-pop-up div只是一个空的

<div id="image-pop-up">

</div>
Run Code Online (Sandbox Code Playgroud)

这不起作用......出了什么问题?怎么解决?

Bar*_*ney 7

我怀疑问题与选择器有关,并且目标元素要么找不到,要么是正确的目标元素.

一些可能是错误的事情:

  1. 双重ID引用是不必要的:它只是另一个可能出错的地方.
  2. 如果#image-pop-up在执行此代码时尚未生成,则永远不会绑定该事件.
  3. submit事件仅触发表单,因此您需要确保这是您要定位的内容.
  4. 你调用preventDefault()evt,但evt没有绑定到events参数.

假设这#submit-comment-form是您正在处理的表单,以下代码应该工作,无论执行时是否有任何元素可用:

$(document).on('submit', '#submit-comment-form', function(evt){
    evt.preventDefault();
})
Run Code Online (Sandbox Code Playgroud)