2013-02-12 51 views
0

我正在尝试开发一个足球队的功能,该功能将使用每个选手的选择框存储多达18名选手(11个首发球员和7个潜分者)。JavaScript while while循环获得选择选项并隐藏其他选择框的选项

当从一个选择框中选择一个玩家时,他们应该隐藏在所有其他选择框中,以停止用户能够再次选择相同的玩家。

我已经写了一个javascript/jquery函数来做这件事,但它非常长时间的啰嗦,我猜测最好的选择使它更易于管理,而不是写一段while循环,但我得到我自己试图编码它感到困惑。

当前的代码(首发)可以在http://jsfiddle.net/aFDjS/

可以看出我是正确的思维是什么,我需要做的是可能有嵌套在另一个while循环while循环忽略当计数像玩家号码一样这样...

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++; 
} 

这是否正确?

+0

为什么不存储t他的玩家ID在复选框名称中?这是访问easyer,你可以使用'document.getElementsByName()'获得所有相同名称的复选框。 – 2013-02-12 11:04:34

回答

0

不,你应该使用for循环。

标准是在计数某物时使用for循环,当您等待事件或值更改时使用while循环。

这些for循环中的逻辑很难遵循,看起来不对。

但不管这个,要做到这一点最简单的方法是使用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/

+0

马特太棒了!接下来的步骤是在每个替代品旁边都有一个隐藏的选择框,每次在阵容中选择一名玩家时都会填充该选择框。一旦选择了一名玩家作为替代者,下拉将会显示在他们旁边,以便他们可以选择他们替换的玩家。 所以实质上这可能是你在这里帮助我的反对,所以是使用select name/id来指定修改的最简单的方法(例如,在我循环计数并设置名称/身份证作为subbedPlayer#我# - - 其中我是计数(12-18))? – CPB07 2013-02-12 15:43:16

0

那么,不知道什么是完整的程序概念,但我认为你的解决方案有点矫枉过正。
我会给每个复选框的名称(例如:"plr"+ID),我会附加一个onclick事件。当事件被触发时,复选框会搜索同名的所有复选框并禁用它们。

function selectPlr(event) { 
    var other = document.getElementsByName(this.name); //Get element collection 
    for(var i=0; i<other.length; i++) { 
     if(other[i]!=this) { //Ignore itself 
     other[i].disabled = this.checked; //Disable if the player is picked, enable if unpicked 
     } 
    } 
} 

当然,类名可以用来代替:

var other = $("input."+this.className); 

这里是active code

0

可能是这样会给你的想法执行:http://jsfiddle.net/2jGDU/

$('#players').change(function() { 
    $('#pl_11').prepend($('option:selected', this).clone()); 
    $('option:selected', this).remove(); 
    if ($('option', this).length <= 8) { 
    $('option:first', this).remove(); 
    $('#sub').prepend($(this).html()); 
    $('option', this).remove(); 
    } 
}); 
相关问题