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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doulongdan2264 2017-09-06 03:36

    use this construction for dynamicaly created objects: $(document).on("click", "elementSelector", function(){ /* function body*/})

    评论
    解决 无用
    打赏 举报
  • dongshuming7131 2017-09-06 03:51

    Create delegated event binding using on like this

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

    Note : Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

    评论
    解决 无用
    打赏 举报
  • drbfxb977777 2017-09-06 03:58

    The jQuery method you're using assumes that the element is already within the DOM (already exists on the page) when your Javascript runs. Because you're adding HTML to the page after your script has run, your use of $(".test") will not catch any HTML added later.

    You have two options:

    1. Query your HTML only once the new HTML has been inserted

    Include your $() query in the same callback where you're inserting your HTML, like this:

    $.post("getId.php", {id:id}, function(data) {
      $(".insertion").html(data);
    
      // this will work now
      $(".test").on("click", function() { ... });
    });
    

    Or, maybe better, scope your jQuery query to only look within the newly inserted HTML:

    $.post("getId.php", {id:id}, function(data) {
      var $insertion = $(".insertion");
      $insertion.html(data);
    
      // only find .test within the new HTML
      $insertion.find(".test").on("click", function() { ... });
    });
    

    2. Change your jQuery syntax to bind an event listener to the body

    As @diavolic points out, jQuery provides a second syntax for .on, where you bind your listener to an element but provide a selector as a second argument. The callback will only fire if the event is triggered on elements matching this selector. By binding the listener to the body tag (which is always present in the DOM) and providing .test as the selector, the .test element doesn't need to exist in the DOM when the javascript runs.

    $(document.body).on("click", ".test", function() {
      // do something
    });
    
    $.post("getId.php", {id:id}, function(data) {
      $(".insertion").html(data);
    });
    

    Either option should work. The first option is a better option if you want to listen for clicks only within a specific element. The second is more reliable if you aren't sure when or where the new HTML will be inserted.

    More information about event delegation can be found here: http://api.jquery.com/on/#direct-and-delegated-events

    评论
    解决 无用
    打赏 举报
  • dqh19413 2017-09-06 05:03
     //for <input type="button" class="test" value="test">
    jQuery(document).ready(function() {
        jQuery('.test').on( 'click', function () {   
        alert('no');    
        });
    }); 
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题