Wondering why the example below doesn\'t work?
Load the list
.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");
});
});
$(document).on('click','ul li a', function(){
// Content Code
});
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).
Try this new code, it removes existing click events for the old elements and then adds them again for both the old and new.
<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>');
$('ul li a').unbind('click', thanks());//Remove existing binds
$('ul li a').bind('click', thanks());//Remove existing binds
return false;
});
function thanks() {
alert('Thank you for clicking');
return false;
});
$('ul li a').bind('click', thanks());
});
</script>
because you are apply the click event before the element is place in the dom you need to use .live()
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/