Wondering why the example below doesn't work?
<a id="load_list" href="#">Load the list</a>
<ul></ul>
<script type="text/javascript">
$(document).ready(function() {
$('#load_list').click(function() {
$('ul').append('<li><a href="#">Click here</a></li>');
return false;
});
$('ul li a').click(function() {
alert('Thank you for clicking');
return false;
});
});
</script>
Because the elements that you are appending do not exist when you define the the click
handler, they are created dynamically. To fix this you can use the delegate() method from jQuery.
$('ul').delegate('a','click',function() {
// your code here ...
});
Online example: http://jsfiddle.net/J5QJ9/
From jQuery 1.7 you can use the .on() handler to bind the newly created element ot the 'click' event:
<script type="text/javascript">
$(document).ready(function() {
$('#load_list').click(function() {
$('ul').append('<li><a href="#">Click here</a></li>').on('click', 'ul li a', function () {
alert('thank you for clicking');
});
});
</script>
(this is with the original example).
$(document).on('click','ul li a', function(){
// Content Code
});
.live is deprecated as of 1.7. Try this (jquery 2.1.4):
Html:
<a id="load_list" href="#">Load the list</a>
<ul></ul>
JQuery:
$(document).ready(function() {
$('#load_list').click(function() {
$('ul').html("");
$("<li/>", {
"class" : "someClass",
text: "Click here",
click: function() {
alert($(this).text());
}
}).appendTo('ul');
});
});
or something like this (but I didn't find how to attach click to the anchor):
$(document).ready(function() {
$('#load_list').click(function() {
$('ul').html("");
$('<li><a href="#">Click here</a></li>').on({
click: function() {
alert("hoi");
}
}).appendTo("ul");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With