javascript - jQuery selector precedence when using pattern matching -
i creating form implements bunch of similar elements. custom select boxes, created out of <ul>s.
some of these elements different in way want mousedown event handled though.
the way have set that, appending _custom_select end of elements class name, treated 1 of these special elements far css concerned.
however, when string selections found inside class name (that coincidentally end _custom_select in order apply proper styling) want use different mousedown event handler.
this relevant section of event listener set up:
$('[class$="_custom_select"] li').mousedown(function(event){ var opt= event.target; if(opt.classname!='li_disabled' && event.which==1) { if(opt.classname=='li_unselected'){ opt.classname= 'li_selected'; } else{ opt.classname= 'li_unselected'; } update_selections(opt.parentelement); } }); $('[class*="selections"]').mousedown(function(event){ var opt=event.target; if(event.which==1){ if(opt.classname=='li_unselected'){ opt.classname= 'li_selected_2'; } else{ opt.classname= 'li_unselected'; } } }); this code works, notice how, in second binding, had bind event listener ul holds li being clicked.(the ul element class name matches pattern) in first 1 however, can bind event listener directly li elements contained within ul.
if change second jquery selector $('[class*="selections"] li') event listener never bound corresponding lis.
what causing behavior?
i aware can check event.target.tagname ensure event bubbling <li>, not question about.
i thought had precedence , listeners weren't being bound because lis have matched second selector matched against first selector.
however, after implementing logging , looking @ dom have determined when change second selector to: $('[class*="selections"] li') neither event listener bound lis match second selector.
here link js fiddle of 'working version'. if add ' li' second selector , try click <li>s in box right, see no longer become green.
jsfiddle
okay, posting jsfiddle. easy fix!
the elements in second li being added dynamically. when bind elements using shortcut methods .click() only binds elements on page when bound
the fix: use .on() method, preferred method per jquery foundation. method allows live binding meaning pick on dynamic elements.
$('[class*="selections"]').on( 'mousedown', 'li', function(event) { var opt = event.target; if (event.which == 1) { if (opt.classname == 'li_unselected') { opt.classname = 'li_selected_2'; } else { opt.classname = 'li_unselected'; } } });
Comments
Post a Comment