javascript - JQuery.live() not working properly -
i know live deprecated in version 1.7 , removed in 1.9 , not recommended anymore. still, preparing interview machine test , hence trying difference between live , on. document says
calling event.stoppropagation() in event handler ineffective in stopping event handlers attached lower in document; event has propagated document.
hence tried this. markup:
<div> <h1> <a href="#"> <span>hello</span> </a> </h1> </div> script:
$(document).ready(function () { $('span').live("click",function () { alert('span'); }); $('a').click(function () { alert('span a'); }); $('h1').click(function () { alert('span h1'); event.stoppropagation(); }); $('div').click(function () { alert('span h1 div'); }); }); i using jquery version 1.7, in both live , on exist.
whats happening:
liveof span not getting called, instead calls directlyclickofa.- if remove other events
livegetting called. - as doc says, doing opposite, i.e it's stopping event bubbling if use
event.stoppropagation();
event handlers attached live attached document. if call event.stoppropagation in callback of live event bubbled document, have no effect directly attached event handlers.
your event.stoppropagation() called when event reaches, h1element, never reach document live event handler attached.
with on can create type of event handling jquery supports. if @ source of jquery, can see in 1.7 live function maps on:
live: function( types, data, fn ) { jquery( this.context ).on( types, this.selector, data, fn ); return this; } the reason live removed make api clearer , more logical when event happens , catched.
edit
your dom , place event handlers attached to:
document $('span').live("click") **not called** (equal to: $(document).on('click', 'span') ) | div $('div').click() **not called** | h1 $('h1').click() + event.stoppropagation() **the propagation (bubbling) stopped here not reaching document** | $('a').click() | span **event happens here , bubbles up**
Comments
Post a Comment