问题
Is there a way I can generate switch statements in jquery/javascript by using some sort of loop to do the work for me? For example, if I had a statement like:
switch ($("#play option:selected").text()) {
case '1':
$("#play_1").slideDown().find("input").addClass("someClass");
break;
case '2':
$("#play_1").slideDown().find("input").addClass("someClass");
$("#play_2").slideDown().find("input").addClass("someClass");
break;
}
This is fine if I only have a few options in my select menu, but what I had 99 options and therefore by case '99' I had to display 99 new divs or whatever they might be?
回答1:
for (var i = 1; i <= $("#play option:selected").text(); ++i) {
$("#play_"+i).slideDown().find("input").addClass("someClass");
}
If you select 10 that loop will find the ten elements from #play_1
to #play_10
and animate them.
回答2:
for (var i = 1; i <= parseInt($("#play option:selected").text(), 10); i++) {
$("#play_" + i).slideDown().find("input").addClass("someClass");
}
来源:https://stackoverflow.com/questions/1169387/switch-statement-and-loops-using-jquery-javascript