JavaScript while循环从其他选择框中获取选择选项和隐藏选项

问题描述:

我正在尝试开发一个足球团队功能,使用每个球员的选择框来存储最多18名球员(11名首发球员和7个替补球员).

I'm trying to develop a football teamline function that will store up to 18 players (11 starting players and 7 subs) using a select box for each player.

从一个选择框中选择一个玩家后,应将其隐藏在所有其他选择框中,以阻止用户再次选择相同的玩家.

When a player is selected from one select box they should then be hidden in all the other select boxes to stop the user from being able to select the same player again.

我已经写了一个javascript/jquery函数来做到这一点,但是它缠绕了很长一段时间,我猜想使它更易于管理的最佳选择是编写一个while循环,但是我自己尝试编写代码感到困惑.

I've written a javascript/jquery function that does this but it is VERY long winded and I'm guessing that the best option to make it a lot more manageable would be to write a while loop but I'm getting myself confused trying to code it.

当前代码(用于起始XI)可以在 http://jsfiddle.net/aFDjS/

The current code (for the starting XI) can be seen at http://jsfiddle.net/aFDjS/

我是否正确地认为我需要做的可能是在另一个while循环中嵌套一个while循环,以便在计数与像这样的球员人数相同时忽略...

Am I right in thinking that what I need to do is probably have a while loop nested inside another while loop to ignore when the count is the same as the player number kind of like this...

i = 1;
playerNo = 1;
while (i < 19) {        
    while (playerNo < 19 && i != playerNo) {
        playerID = $("#player" + i + "Name option:selected").val();
        $("select#player" + playerNo + "Name >option" ).filter( "[class='"+ playerID +"']" ).hide();
        $("select#player" + playerNo + "Name >option" ).filter( "[class!='"+ playerID +"']" ).show();
        playerNo++;
    }
    i++;
}

这是正确的路线吗?

不,您应该使用for循环.

标准是在计数事件时使用for循环,而在等待事件或值更改时使用while循环.

The standard is to use for loops when counting something and while loops when you're waiting for an event or value to change.

这些for循环中的逻辑很难遵循,而且看起来还是错误的.

The logic in those for loops is hard to follow and looks wrong anyway.

但是无论如何,最简单的方法是使用jquery的功能:

But regardless of this, the easiest way to do this is using the power of jquery:

$(function() {
    $("select").on("change", function() {
        //reset to showing all the options
        $("select option").show(); 

        //for each selected option
        $("select option:selected").each(function() {
            var optionSelected = this;
            var playerID = $(this).attr("class");
            //hide the option in all the other dropdowns
            $("option." + playerID).each(function() {
                if(this != optionSelected) {
                    $(this).hide();
                }
            });
        });
    });
});

此处的工作示例:

http://jsfiddle.net/4avwm/1/