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?
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
Jquery Live
.click binds to what is presently visible to jQuery. You need to use .live:
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
After jquery 1.7 on method can be used and it really works nice
see it in action http://jsfiddle.net/rahulchaturvedie/CzR6n/
You need to add a proper button click function to give a proper result