I don't want to use $(document).on('click', handler)
or $('.class').on('click', handler)
... I prefer to use $('.class').click();
To me it's easier to find your way in the code but I don't know if it's faster or not.
If I add a new element in the DOM like :
function addElementThenBindAction(){
var html = $ ("<div><a id="#myid">Link me</a></div>");
html.click( addElementThenBindAction() );
$('body').append( html );
}
$('#aButtonFromDom').click(function(){
addElementThenBundAction();
});
Is that faster than -
function addHtml(){
var html = $ ("<div><a id="#myid">Link me</a></div>");
$('body').append('html');
}
$(document).on('click', '#myId', function(){
addHtml();
});
$('#aButtonFromDom').click(function(){
addHtml();
});
As the jQuery documentation states:
.click( handler )
This method is a shortcut for
.on( "click", handler )
In short the answer is that the .on()
function will be "faster" than the .click()
simply because fewer functions are being called. However the performance gain/loss that you will see is really insignificant.
Only if you would be dealing with a lot of elements would you maybe be able to see/feel the performance differences.
I found a jsperf that deals with this comparison along with some other comparisons - http://jsperf.com/jquery-on-versus-click/10 . It's not using the newest jQuery version, but I doubt that the differences would be note worthy.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.