why does jquery (1.6.x) context work for bind() and not live()?
Works:
var magic_div = $('<div>');
$('body').html(magic_div);
$(magic_div).append('<a href="#" class="bind-event">click</p>');
$( '.bind-event' , magic_div).bind('click' , function(){ console.log('bind works'); });
Doesn't work:
var magic_div = $('<div>');
$('body').html(magic_div);
$(magic_div).append('&开发者_StackOverflow中文版lt;a href="#" class="bind-event">click</p>');
$( '.bind-event' , magic_div).live('click' , function(){ console.log('bind works'); });
This probably explains it, but I don't understand why it shouldn't work if DOM elements are present.
If you change j('#bind-event',magic_div)
with j('#bind-event')
, it works fine in both cases. (There's no point in applying a context to an ID.)
You are binding click
event on an anchor without preventing the default behavior of it. So when you click on the anchor it triggeres the click
event and after that it tries to redirect to href
set into it.
Now since bind
directly attaches the event handler on the element it works where as live
binds the click
event to the DOM's document element. As browser events bubble up through the DOM tree, the click event is triggered for any matching elements. Since you are not preventing the default behavior of the anchor the event is not getting bubbled. Try this it will work.
var magic_div = j('<div>');
j('body').html(magic_div);
j(magic_div).append('<a href="#" id="bind-event">click</p>');
j( '#bind-event' , magic_div).live('click' , function(e){
e.preventDefault();
console.log('bind works');
});
Had a conversation today and learned that live()
is less forgiving and will not accept a jQuery object, but will accept a DOM element.
The following works:
var magic_div = $('<div>');
$('body').html(magic_div);
$(magic_div).append('<a href="#" class="bind-event">click</p>');
$( '.bind-event' , magic_div.get(0) ).live('click' , function(){ console.log('bind works'); });
精彩评论