Charlie lee
Charlie lee

Reputation: 71

add event which is geneerated by jquery append method

I have a question about attach event.

First: after document is ready, I made ajax and success

Second: after ajax success, I append some code to body tag

Third: I'd like to attach event which is created at Second.

Below is my code

<html>
<head>
<meta charset="utf-8" />
<title></title>
<!--jquery, cookie import-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>

<body>
<script>
  $(document).ready(function(){
    $.ajax({
      url: '/phone',
      type:'post',
      success:function(){
        $('body').append('<div class="test">hi</div>')
      }
    })
  })

  $('.test').on('click',example)
  function example(){
    alert('success');
  }
</script>
</body>
</html>

after I run this, when I click the div, no alert popup..

IS there anyone who can explain why this doesn't work?

Upvotes: 0

Views: 28

Answers (1)

Mitya
Mitya

Reputation: 34598

Yes - it's logical. You're binding the event to an element that doesn't yet exist. It's not future-aware; it won't attach itself to any elements that turn up in the future that match the selector.

Instead, delegate the event. This is good practice generally for events except in simple cases involving single elements or elements you know for sure exist at the time of binding the event.

$('body').on('click', '.test', example);
function example() {
    alert('success');
}

Upvotes: 1

Related Questions