dousheng3364 2017-09-06 03:27
浏览 74
已采纳

使用jQuery将事件添加到动态生成的元素[duplicate]

This question already has an answer here:

I tried to add a form from a php file to another php file using jQuery, and I added an event to my added input(submit) button, but it's nt work,

I have seen some answers that propose using the method $elm.on("click",function() instead of of $elm.click(function(), but it still not work.

So here is my code :

<div id="update" class="third">
  <div class="updatingzone">
    You will have to rwrite all the data again
    <form method="post" class="updating">
      <input type="text" name="id" class="id" style="width:40px;" />
      <input type="submit" id="button" value="Insert" />
    </form>
    <input type="submit" id="button" class="cancel" value="Cancel" />
  </div>
<div class="insertion"></div>
</div>

when I press the Button Insert this php file is added :

<?php require_once "connexion.php";
 $gdb = new GestionBD();
 $id = $_POST["id"];

 $req = "select * from utilisateurs WHERE id='$id'";
 $results = $gdb->selectFromBD($req);


 foreach ($results as $result):
  ?>
  <form class="insertMode" method="post">
    <input type="text" value="<?php echo $result->nom;?>" class="nom"                name="nom" /><br />
    <input type="text" value="<?php echo $result->email;?>" class="email" name="email" /><br />
    <input type="text" value="<?php echo $result->sexe;?>" class="sexe" name="sexe" /><br />
    <input type="text" value="<?php echo $result->age;?>" class="age" name="age" /><br />
    <input class="test" id="button" type="submit" value="Add" />
  </form>
<?php endforeach;?>

When I press the button with the class test I don't get an alert with "no" message, as you can see in the script :

$(".updating").submit(function () {
  var id = $(".id").val()
  $(".insertion").show()
  $.post("getId.php",{id:id},function (data) {
    $(".insertion").html(data)
  });
  return false;
});

$(".test").click(function () {
  alert("no");
});

And i am sorry if this is long.. Thank you people

</div>
  • 写回答

5条回答 默认 最新

  • dowaw80220 2017-09-06 03:48
    关注

    Since the element is being generated dynamically, you need to use event delegation.

    $(document).on("click",".test", function () {
     console.log("no");
    });
    

    Reference Document: https://learn.jquery.com/events/event-delegation/

    Hope this will help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值