jQuery function not binding to newly added dom ele

2019-01-03 23:41发布

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?

13条回答
Deceive 欺骗
2楼-- · 2019-01-03 23:53

Or just run the script at the end of your page

查看更多
地球回转人心会变
3楼-- · 2019-01-03 23:54
$('.btn_test').click

will add the handler for elements which are available on the page (at this point 'test' does not exist!)

you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..

$('.btn_test').live(function() { alert('test'); });
查看更多
放荡不羁爱自由
4楼-- · 2019-01-03 23:59

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/

查看更多
相关推荐>>
5楼-- · 2019-01-04 00:00

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

查看更多
在下西门庆
6楼-- · 2019-01-04 00:01

you need live listener instead of click:

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

The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards

查看更多
可以哭但决不认输i
7楼-- · 2019-01-04 00:02

Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/

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

Edit: live() is deprecated and you should use on() instead.

$(".btn_test").on("click", function(){ 
   alert("test");
});
查看更多
登录 后发表回答