I've only really started using this site and alredy I am very impressed by the community here! This is my third question in less than three days. Hopefully I'll be able to start answering questions soon instead of just asking them!
I'm fairly new to jQuery and can't find a decent tutorial on Arrays. I'd like to be able to create an array that targets several ID's on my page and performs the same effect for each.
For example I have tabs set up with the following:
$('.tabs div.tab').hide();
$('.tabs div:first').show();
$('.tabs ul li:first a').addClass('current');
$('.tabs ul li a').click(function(){
$('.tabs ul li a').removeClass('current');
$(this).addClass('current');
var currentTab = $(this).attr('href');
$('.tabs div.tab').hide();
$(currentTab).show();
return false;
});
I've used the class .tag to开发者_JS百科 target the tabs as there are several sets on the same page, but I've heard jQuery works much faster when targetting ID's
How would I add an array to the above code to target 4 different ID's? I've looked at
var myArray = new Array('#id1', 'id2', 'id3', 'id4');
And also
var myValues = [ '#id1', 'id2', 'id3', 'id4' ];
Which is correct and how do I then use the array in the code for my tabs...?
First off, what you need to do is distinguish between JavaScript (the language) and jQuery (the framework library).
Arrays are a feature of the language JavaScript and jQuery has very little to do with Arrays other than using it as a data structure here and there.
Also I doubt that using an Array/List of IDs is much faster than using a class, which IMHO would be the cleaner solution.
Nevertheless you can do it like this:
You could loop over an Array of Strings containing your IDs and repeat your code block for each of the them instead of referring to the class. Something like this:
$.each(['#id1', '#id2', '#id3', '#id4' ], function(id) {
$(id + ' div.tab').hide();
$(id + ' div:first').show();
$(id + ' ul li:first a').addClass('current');
$(id + ' ul li a').click(function(){
// etc.
});
});
However using the class is (as I mentioned) much cleaner, and probably easier, because that way you just need to "drop" your code into the page and it will do its thing without you needing to worry about possibly changing the list of IDs for each page.
Use commas in the selector. For instance:
$('#id1, #id2, #id3, #id4').hide();
You don't need an explicit array here. However, note that in JavaScript,
new Array('a', 'b', 'c', 'd')
and
['a', 'b', 'c', 'd']
mean the same.
Do you mean you want a selector with many Ids in it?
like:
$('#id1,#id2,#id3,#id4').hide()
or do you actually want to create the selector from the array? You can do that too
var myArray = new Array('#id1', '#id2', '#id3', '#id4');
$(myArray.join()).hide();
Hope it helps
You can use $.each
here
$.each(['id1', 'id2', 'id3', 'id4' ], function() {
/* whatever you want to do with each item.
this will reference the item in the current iteration */
});
精彩评论