Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function not binding to newly added dom elements

Here's index.html:

<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
  <script type="text/javascript">

    $(document).ready(function() {
      $('.btn_test').click(function() { alert('test'); });
    });

    function add(){
      $('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
    }

  </script>
</head>
<body>
  <a href="javascript:;" class="btn_test">test1</a>
  <a href="javascript:;" onclick="add()">add</a>
</body>

If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.

Could you explain it?

like image 589
Ralsk28 Avatar asked Jun 30 '11 15:06

Ralsk28


2 Answers

For users coming to this question after 2011, there is a new proper way to do this:

$(document).on('click', '.btn_test', function() { alert('test'); });

This is as of jQuery 1.7.

For more information, see Direct and delegated events

like image 160
Moshe Katz Avatar answered Oct 14 '22 01:10

Moshe Katz


You need to use a "live" click listener because initially only the single element will exist.

$('.btn_test').live("click", function() { 
   alert('test'); 
});

Update: Since live is deprecated, you should use "on()":

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

http://api.jquery.com/on/

like image 34
Doug Molineux Avatar answered Oct 14 '22 03:10

Doug Molineux