这里有继续选择和禁用我们想要的所有时间的代码。
首先是启用每个选项,然后查看所选值,然后禁用与所选值一致的选项。
这两个步骤至关重要,因为如果您再次选择,之前的禁用值将继续禁用。
最新版本
更优雅的方式,我们使用 map() (in stackoverflow there is a good explanation about this method) 和 filter() jquery 函数来完成这项工作。行数更少,我认为性能相同或更好。
http://www.jsfiddle.net/dactivo/keDDr/
$("select").change(function()
{
$("select option").attr("disabled",""); //enable everything
//collect the values from selected;
var arr = $.map
(
$("select option:selected"), function(n)
{
return n.value;
}
);
//disable elements
$("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
}).attr("disabled","disabled");
});
新版本
我已经编辑了我的答案,这是我的最终版本:
http://www.jsfiddle.net/dactivo/kNbWc/
$("select").change(function()
{
$("select option").attr("disabled",""); //enable everything
DisableOptions(); //disable selected values
});
function DisableOptions()
{
var arr=[];
$("select option:selected").each(function()
{
arr.push($(this).val());
});
$("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1;
}).attr("disabled","disabled");
}
旧版本
http://www.jsfiddle.net/AyxL3/
$("select").change(function()
{
$("select option").attr("disabled",""); //enable everything
DisableOptions(); //disable selected values
});
function DisableOptions()
{
$("select option").filter(function()
{
var bSuccess=false; //will be our flag to know it coincides with selected value
var selectedEl=$(this);
$("select option:selected").each(function()
{
if($(this).val()==selectedEl.val())
{
bSuccess=true; //it coincides we will return true;
return false; // this serves to break the each loop
}
});
return bSuccess;
}).attr("disabled","disabled");
}