JS for loop issue
I've got the below code...
var ToggleButtons=ne开发者_JAVA技巧w Array();
ToggleButtons[0] = "#Click";
ToggleButtons[1] = "#DoubleClick";
ToggleButtons[2] = "#Drag";
ToggleButtons[3] = "#RightClick";
ToggleButtons[4] = "#MiddleClick";
function SelectButton(id) {
var x = 0;
for (x = 0; x++; x < ToggleButtons.length) {
if (x == id) {
$(ToggleButtons[x]).addClass('ToggleButtonSelected');
} else {
$(ToggleButtons[x]).removeClass('ToggleButtonSelected');
}
}
}
however, when I call SelectButton(n) with n=0->4, it hits the for() line and jumps straight to the closing brace.
on the for() line before it executes, Firebug shows (eg)
id=2
ToggleButtons.length=5
x=0
I've got the feeling I'm missing something obvious but I'm not sure what,
Many thanks
Your for()
order is mixed up, this:
for (x = 0; x++; x < ToggleButtons.length) {
Should be:
for (x = 0; x < ToggleButtons.length; x++) {
You can use .toggleClass("class", bool)
to shorten it a bit though, like this:
function SelectButton(id) {
for (var x = 0; x < ToggleButtons.length; x++) {
$(ToggleButtons[x]).toggleClass('ToggleButtonSelected', x === id);
}
}
An even better approach would be to cache the selectors so they're not run each time, like this:
var ToggleButtons = [$("#Click"), $("#DoubleClick"), $("#Drag"), $("#RightClick"), $("#MiddleClick")];
function SelectButton(id) {
$(".ToggleButtonSelected").removeClass('ToggleButtonSelected');
ToggleButtons[id].addClass('ToggleButtonSelected');
}
The parts of the for loop are the wrong way around, it should be initialisation, condition, then incrementation:
for (x = 0; x < ToggleButtons.length; x++)
Change this line:
for (x = 0; x++; x < ToggleButtons.length) {
to this:
for (x = 0; x < ToggleButtons.length; x++) {
精彩评论