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 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗