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.
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.
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);
JS Fiddle Example
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(){ ... });
}
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',
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/
精彩评论