简体   繁体   中英

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 happening?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM