[英]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);
wizardScreens
定义为$(".wizardScreen", wizard);
, where wizard
is a DOM element. ,其中
wizard
是一个DOM元素。 Within the loop, myScreen
is set to a string, instead of being a DOM element. 在循环中,
myScreen
设置为字符串,而不是DOM元素。 Can anyone explain why that is happening? 任何人都可以解释为什么会这样吗?
jQuery collections already have a built-in iteration function: jQuery集合已经有了内置的迭代函数:
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. 一般来说,答案是
.each
,但它会为每个DOM元素调用一个函数,这比使用jQuery函数一样,这个函数一次操作jQuery对象中的所有节点,所以最好尽可能避免它。 In this case it is definitely possible: 在这种情况下,它绝对是可能的:
wizardScreens.hide().eq(step).show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.