JavaScript while循环获取选择选项并隐藏其他选择框中的选项

我正在尝试开发一个足球队线function,使用每个球员的选择框可存储多达18名球员(11名首发球员和7名球员)。

当从一个选择框中选择一个播放器时,它们应该隐藏在所有其他选择框中,以阻止用户再次选择同一个播放器。

我已经编写了一个javascript / jquery函数来做到这一点,但是它非常冗长,而且我猜想让它更易于管理的最佳选择是编写一个while循环,但我让自己感到很困惑编码吧。

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

我是否正确地认为我需要做的事情可能是将一个while循环嵌套在另一个循环中以忽略当计数与玩家数量相同时…

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

这是沿着正确的方向吗?

不,你应该使用for循环。

标准是在计算某些内容时使用for循环, while在等待事件或值更改时使用while循环。

for循环中的逻辑难以理解,无论如何看起来都是错误的。

但无论如何,最简单的方法是使用jquery的强大function:

 $(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/

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

  function selectPlr(event) { var other = document.getElementsByName(this.name); //Get element collection for(var i=0; i 

当然,可以使用类名:

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

这是活动代码 。

可能这会给你实现的想法: 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(); } });