Why does this happen in jQuery 1.7.x?

The following snapshot shows what the problem is:

var $div = $('<div>'); $('span').live('click', function() { this.innerHTML = 'changed'; }); $div.append( $('<span>span</span>').click() ); $div.appendTo('body'); ​ 

This works as expected in jQuery 1.6.x , but not in 1.7.x

Why doesn't it work in 1.7.x? This is mistake? Is there any way to make it work in 1.7.x?

EDIT: .on won't change anything !!

+4
source share
4 answers

The way events are handled has changed in version 1.7. Before <span> is added to the DOM, events triggered on it will not bubble up to <body> as they once were (mistakenly, in my opinion, behavior 1.7 makes a lot more sense).

Perhaps the event fires on <span> , but since the event does not bubble on <body> , the actual handler that deals with your .live() installation cannot be called.

edit - this may be a document element for which events are bubbling; no matter the point is the same.

change again - Here you can do this work so that you can run handlers before adding your elements to the DOM:

 $('<div></div>').on('click', 'span', function() { this.innerHTML = "Changed!"; }).append($('<span>span</span>')) .find('span').click().end() .appendTo($('body')); 

This sets the click handler as a delegated handler on the nascent <div> directly. Then, adding a new <span> to this element, then you can call "click" on <span> and call the handler. This happens before all this is added to <body> .

+5
source

As with jQuery 1.7, the .live () method is deprecated . Use .on () to attach event handlers.

http://api.jquery.com/live/ (as commentators note, this still works in jQ 1.7)

For your editing:

to try

 var $div = $('<div>'); var span = $('<span>span</span>'); span.click(function() { this.innerHTML = 'changed'; }); $div.append( span.click() ); $div.appendTo('body'); 

http://jsfiddle.net/3BTaz/3/

+3
source

Working solution for 1.6 and 1.7

 var $div = $('<div>'); $('span').live('click', function() { this.innerHTML = 'changed'; }); $div.append('<span>span</span>'); $div.appendTo('body'); $('span').trigger('click'); 

Demo


However, omit the risk of using an obsolete function with live to on replaced.

 $('span').on('click', function() { this.innerHTML = 'changed'; }); 
+2
source

You pass the result of .click() to .append() . The interesting thing is that it worked in version 1.6, since nothing is returned from your function. This is likely due to internal changes to the .live operation or the way .click calls its listeners.

Note how this works in version 1.7

 var $div = $('<div>'); $('span').live('click', function() { this.innerHTML = 'changed'; }); $div.append( $('<span>span</span>') ); $div.appendTo('body'); $('span').click(); 
0
source

Source: https://habr.com/ru/post/1400577/


All Articles