Friday, 15 August 2014

jquery - Same selector with multiple functions/event handlers -



jquery - Same selector with multiple functions/event handlers -

pretty simple question here: there improve way write code?

$('.icmenu span.menu').each(function() { // }); $('.icmenu span.menu').click(function() { // else });

i'm using same selector twice, there improve way should writing this?

options:

use chaining suggested

$('.icmenu span.menu').each(function() { // }).click(function() { // else });

or utilize local variable avoid running jquery selector twice:

var $menus = $('.icmenu span.menu'); $menus.each(function() { // }); $menus.click(function() { // else }); basic rule:

the key avoid running selector more 1 time has big overhead.

delegated events:

if elements ever dynamically created, move click delegated on event handler anyway, question become non-issue (they same selector, separated in time):

$(document).on('click', '.icmenu span.menu', function(){ // on dynamically created elements });

in delegated event handler, selector run after event caught on ancestor (in case document). function then applied matching elements caused event.

jquery

No comments:

Post a Comment