Reputation: 16596
Why this code works (see code at jsfiddle)
$(document).ready(function() {
var html = '<div><a href="javascript:">click me</a></div>';
var $div = $(html);
$div.find('a').bind('click', function() { //attention on bind
alert('Hi');
});
$('#test').append($div);
});
but the same code with .bind('click'
replaced with .live('click'
is not working? Why?
Thank you.
Upvotes: 4
Views: 1467
Reputation: 56
Great article on [differences between jQuery .bind() vs .live() vs .delegate() vs .on() : http://www.elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/
Upvotes: 0
Reputation: 11
You can use .bind() on a specific html element (here : $div > a) but the .live() function is different : it applies to elements of the same kind (like $("div > a")).
So you can change $div.find('a').bind('click',
in $('div > a').live('click',
Upvotes: 0
Reputation: 35793
You can use delegate instead like this:
var $div = $('<div><a href="javascript:">click me</a></div>');
$div.delegate('a', 'click', function() {
alert('Hi');
});
$('#test').append($div);
Upvotes: 3
Reputation: 16460
jQuery documentation says:
DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector.
So if you change $div.find('a').bind('click'
to $('#test a').live('click'
it would work.
Upvotes: 5
Reputation: 9929
Maybe you should not replace $(document).ready with .live('click') by nest it. The cause of your problem may be that the document is not fully loaded yet, so the binding is not working.
So try something like:
$(document).ready(function() {
$('mybutton').live('click', function(){ ... });
}
Upvotes: 0