开发者

Iteration over jquery object returning string instead of dom elements

开发者 https://www.devze.com 2023-01-13 03:52 出处:网络
I have the following loop: for(var myScreen in wizardScreens){ if(step==index)$(myScreen).show(); else $(myScreen).hide();

I have the following loop:

for(var myScreen in wizardScreens){
    if(step==index)$(myScreen).show();
    else $(myScreen).hide();
    index++;
}

wizardScreens is defined as $(".wizardScreen", wizard);, where wizard is a DOM element. Within the loop, myScreen is set to a string, instead of being a DOM element. Can anyone explain why that is happe开发者_高级运维ning?


jQuery collections already have a built-in iteration function:

wizardscreens.each(function (index, screen) {
  if (index == step)
    $(screen).show();
  else
    $(screen).hide();
}

Or perhaps even better for your use:

var activescreen = wizardscreens.eq(step);
activescreen.show();
wizardscreens.not( activescreen[0] ).hide();

Which avoids explicit iteration altogether.


In general, the answer is .each, but that calls a function for every DOM element, which is slower than using jQuery functions which manipulate all nodes in a jQuery object at once, so it's best to avoid it whenever possible. In this case it is definitely possible:

wizardScreens.hide().eq(step).show();
0

精彩评论

暂无评论...
验证码 换一张
取 消