switch statement and loops using jquery/javascript

六眼飞鱼酱① 提交于 2019-12-24 21:19:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!