admin管理员组文章数量:1277404
I am trying to loop through an array of jquery objects I have created that are hidden when clicked. Right now Im not sure where I am going wrong with this and was wondering if anyone could explain what I need to do to make it work?
I have created a fiddle here /
All advice much appreciated
Kyle
I am trying to loop through an array of jquery objects I have created that are hidden when clicked. Right now Im not sure where I am going wrong with this and was wondering if anyone could explain what I need to do to make it work?
I have created a fiddle here http://jsfiddle/hd5qa/3/
All advice much appreciated
Kyle
Share Improve this question asked Oct 9, 2011 at 22:04 stylerstyler 16.5k25 gold badges85 silver badges139 bronze badges 1- the reason I have created objects is because I want to use them multiple times – styler Commented Oct 9, 2011 at 22:11
5 Answers
Reset to default 6The problems with your fiddle were as follows:
1) You hadn't included the jQuery library.
2) You hadn't closed the each
loop correctly (missing parenthesis).
3) You were missing the id
selector #
from "myButton".
Here's an updated, working fiddle.
Note, however, that you could simply do this:
$("#blue, #red, #green, #black, #purple, #orange").hide();
Or better, put all of those in a containing parent element, and simply hide that, or use $("#parent div").hide();
.
You can store the result of that selection in a single variable, rather than the 6 you currently have, as jQuery methods tend to operate on each element in the matched set without the need for a loop.
is there a reason you want to do this trough an array of objects?
you could simplify it all by adding your selectors like this:
$('#blue, #red, #green, #black, #purple, #orange').hide();
There are three problems:
- You run the code with the MooTools library instead of jQuery.
- You forgot
#
in the selector for the button. - You forgot a
);
at the end of the$.each
loop.
http://jsfiddle/Guffa/hd5qa/5/
$(myArray).each(function(index, element){
element.hide();
});
you may wanna try something like this!
var myArray = [$blue, $red, $green, $black, $purple, $orange];
$('#myButton').click(function() {
$(myArray).each(function(index, element) {
$(element).hide();
});
});
You can see it running here: http://jsfiddle/hd5qa/3/
I prefer this way:
var elements = $("div");
var numOfElements = elemenets.length;
for(var i=0; i<numOfElements; i++) {
var element = elements.eq(i);
element.hide();
}
本文标签: javascripthow to loop through an array of jquery objects and hide() each of themStack Overflow
版权声明:本文标题:javascript - how to loop through an array of jquery objects and .hide() each of them - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741292819a2370646.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论