开发者

Iteration over jquery object returning string instead of dom elements

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜