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?
Or just run the script at the end of your page
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..You need to use a "live" click listener because initially only the single element will exist.
Update: Since live is deprecated, you should use "on()":
http://api.jquery.com/on/
For users coming to this question after 2011, there is a new proper way to do this:
This is as of jQuery 1.7.
For more information, see Direct and delegated events
you need live listener instead of click:
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 afterwardsUse Jquery live instead. Here is the help page for it http://api.jquery.com/live/
Edit:
live()
is deprecated and you should useon()
instead.