random - jQuery show and hide does not work consistently -
i'm attempting make button display random element when clicked using show/hide. sets element hidden first stop duplicates, shown. doesn't show.
the fiddle clearer explanation: http://jsfiddle.net/qafqn/.
simplified code:
this.uiselect = function(){ var length = $("#ui li").length; var ran = math.floor(math.random()*length); $('#ui li').hide(); $("#ui li:nth-child(" + ran + ")").show(); }; $(document).ready(function(){ $('#mangle').click(function(){ uiselect(); }); });
use :eq()
instead of :nth-child()
. have quite different meaning. former refers element's position in jquery collection, while latter refers position among dom siblings. these not same in situation.
consider following markup:
div > ul > li 1 > li 2 > ul > li 3 > li 4 > li 5
the query $('div li:eq(2)')
return li 3
(indices zero-based), because third element in collection. on other hand, $('div li:nth-child(3)')
(indices one-based here, why wrote 3 instead of 2) return li 5
, because third element in group, among siblings.
you can save ugly string concatenation , duplicate dom lookups if use .eq()
instead of :eq()
, chaining this:
$("#ui li").hide().eq(ran).show();
Comments
Post a Comment