最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using arrays to store multiple IDs or classes, and then manipulating them in functions - Stack Overflow

programmeradmin3浏览0评论

I have a set of classes stored in a JavaScript array called 'targets' as follows:

HTML

<div id="one">1</div>
<div id="two">2</div>
<div id="three">3</div>
<div id="four">4</div>
<div id="five">5</div>
<div id="six">6</div>
<div id="seven">7</div>
<div id="eight">8</div>
<div id="nine">9</div>
<div id="ten">10</div>

JavaScript — Array

var targets = ["#one", "#two", "#three", "#four", "#five", "#six", "#seven", "#eight", "#nine", "#ten"];

I would then like to manipulate them to use in functions. Depending on my situation, I'd either want to target one specific ID from the array, or all entries in the array at once. I do understand that each entry into an array is given a unique index number, starting with 0. Therefore, #one is index 0, and #ten is index 9.

I also understand that I can use for loops with arrays, that will cycle through each entry. My issue is that I can't seem to get my function working when it is called from a click event (on an input type="button" element).

Here are two examples of my code. One targets one specific entry, the other targets them all. Or at least, that is what it should be doing. Chrome's console shows no errors with my code, and I have never really worked with arrays, so this is a first for me.

JavaScript — Attempting to Target a Single Entry (Working)

$(targets[0]).addClass('hide').removeClass('show');

JavaScript - Attempting to Target All Entries I

$(targets).each(function() {
    $(this).addClass('hide').removeClass('show');
});

JavaScript - Attempting to Target All Entries II

targets.forEach(function() {
    $(targets).addClass('hide').removeClass('show');
});

JavaScript - Attempting to Target All Entries III

var i;
for ( i = 0; i < targets.length; ++i ) {
    $(targets).addClass('hide').removeClass('show');
}

Also, I know that jQuery allows you to manipulate multiple classes and/or IDs at once by passing multiple values through the $() part of the code, but I'm in a predicament where the entries of the array will be different, depending on user input, and I feel that I will be manipulating in excess of 250 different IDs and classes in total. I've simply omitted the HTML code to the first 10 elements.

The majority of the 250 IDs/classes, are located on <option> elements. The .show and .hide classes used in the code are not applied directly to the <option> elements themselves, but to <select> elements that contain these options. Each <select> element has a unique ID.

If I can just figure out how to do this with arrays, everything will be fine.

Thanks.

I have a set of classes stored in a JavaScript array called 'targets' as follows:

HTML

<div id="one">1</div>
<div id="two">2</div>
<div id="three">3</div>
<div id="four">4</div>
<div id="five">5</div>
<div id="six">6</div>
<div id="seven">7</div>
<div id="eight">8</div>
<div id="nine">9</div>
<div id="ten">10</div>

JavaScript — Array

var targets = ["#one", "#two", "#three", "#four", "#five", "#six", "#seven", "#eight", "#nine", "#ten"];

I would then like to manipulate them to use in functions. Depending on my situation, I'd either want to target one specific ID from the array, or all entries in the array at once. I do understand that each entry into an array is given a unique index number, starting with 0. Therefore, #one is index 0, and #ten is index 9.

I also understand that I can use for loops with arrays, that will cycle through each entry. My issue is that I can't seem to get my function working when it is called from a click event (on an input type="button" element).

Here are two examples of my code. One targets one specific entry, the other targets them all. Or at least, that is what it should be doing. Chrome's console shows no errors with my code, and I have never really worked with arrays, so this is a first for me.

JavaScript — Attempting to Target a Single Entry (Working)

$(targets[0]).addClass('hide').removeClass('show');

JavaScript - Attempting to Target All Entries I

$(targets).each(function() {
    $(this).addClass('hide').removeClass('show');
});

JavaScript - Attempting to Target All Entries II

targets.forEach(function() {
    $(targets).addClass('hide').removeClass('show');
});

JavaScript - Attempting to Target All Entries III

var i;
for ( i = 0; i < targets.length; ++i ) {
    $(targets).addClass('hide').removeClass('show');
}

Also, I know that jQuery allows you to manipulate multiple classes and/or IDs at once by passing multiple values through the $() part of the code, but I'm in a predicament where the entries of the array will be different, depending on user input, and I feel that I will be manipulating in excess of 250 different IDs and classes in total. I've simply omitted the HTML code to the first 10 elements.

The majority of the 250 IDs/classes, are located on <option> elements. The .show and .hide classes used in the code are not applied directly to the <option> elements themselves, but to <select> elements that contain these options. Each <select> element has a unique ID.

If I can just figure out how to do this with arrays, everything will be fine.

Thanks.

Share Improve this question edited Jul 5, 2014 at 20:04 DylRicho asked Jul 5, 2014 at 19:41 DylRichoDylRicho 9251 gold badge12 silver badges25 bronze badges 2
  • far too much use of each . Can perform most jQuery methods on the whole collection. $(selector) creates an array of the elements within the jQuery object – charlietfl Commented Jul 5, 2014 at 19:48
  • overall I would say your approach is more plicated than it needs to be – charlietfl Commented Jul 5, 2014 at 19:54
Add a ment  | 

3 Answers 3

Reset to default 4

You have to join the array in to a string that is a valid jQuery selector

$(targets.join(', ')).addClass('hide').removeClass('show');

This will give you

$("#one, #two, #three ...")

which is valid, an array of ID's is not a valid selector

Also note that showing and hiding option elements is not cross browser

Commenting on your approaches in order:

JavaScript — Attempting to Target a Single Entry (Working)

This one is working (as you say). You can use similar techniques to get at ALL elements in the array of id-s:

$(targets[0]).addClass('hide').removeClass('show');
$(targets.join(",")).addClass('hide').removeClass('show');

However the mon way is to add a class attribute rather than an id. After all - remember - that's what classes are for. Any DOM element can (and usually does) have a multitude of classes.

<div id="one" class="number">1</div>
<div id="two" class="number">2</div>
<!-- ... and so on -->

The above two lines bee equivalent to:

// These two lines are each equivalent to $(target[0])
$(".number").eq(0).addClass('hide').removeClass('show'); // or even...
$(".number")[0].addClass('hide').removeClass('show');

// This is equivalent to $(target.join(","))
$(".number").addClass('hide').removeClass('show');

JavaScript - Attempting to Target All Entries I

The .each function can only be called on jQuery objects. You can't use it on an array, but you can use $.each instead:

$.each(targets, function(idx, obj) {
    $(obj).addClass('hide').removeClass('show');
});

JavaScript - Attempting to Target All Entries II

When using forEach, you need to (ok, not need to, but at least should) make use of the parameters passed to your callback:

targets.forEach(function(elt, idx, arr) {
    $(elt).addClass('hide').removeClass('show');
    // ... OR ...
    $(arr[idx]).addClass('hide').removeClass('show');
    // ... OR ...
    $(targets[idx]).addClass('hide').removeClass('show');
});

JavaScript - Attempting to Target All Entries III

$(targets) selects nothing. It doesn't throw an error (though it probably ought to). You access array elements with the [index] notation:

for (var i = 0; i < targets.length; ++i ) {
    $(targets[i]).addClass('hide').removeClass('show');
}

In your for-loop you're query-ing the whole list everytime and not specific elements, (add [i] to targets)

var i;
for ( i = 0; i < targets.length; ++i ) {
    $(targets[i]).addClass('hide').removeClass('show');
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论