JQuery-禁用选择的选项

需要禁用选择框中已经选择的选项使用 jQuery。我希望它像 选择灰色。

测试我的例子 给你

//JS
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);


theDiv.slideDown().removeClass("hidden");
});




$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
});


//HTML
<body>
<div class="selectContainer">
<select id="theSelect">
<option value="">- Select -</option>
<option value="Patient">Patient</option>
<option value="Physician">Physician</option>
<option value="Nurse">Nurse</option>
</select>
</div>
<div class="hidden isPatient">Patient <a href="#" class="remove" rel="Patient">remove</a></div>
<div class="hidden isPhysician">Physician <a href="#" class="remove" rel="Patient">remove</a></div>
<div class="hidden isNurse">Nurse <a href="#" class="remove" rel="Patient">remove</a></div>
</body>​

更新 : 这是 成品溶液。感谢帕特里克和西蒙。

280840 次浏览

这似乎行得通:

$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);


theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});




$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});

将此行添加到 change事件处理程序

    $("#theSelect option:selected").attr('disabled','disabled')
.siblings().removeAttr('disabled');

这将禁用选定的选项,并启用任何以前禁用的选项。

编辑:

如果您不想重新启用前面的代码,只需删除行的这一部分:

        .siblings().removeAttr('disabled');

编辑:

Http://jsfiddle.net/pd5nk/1/

若要在单击删除时重新启用,请将此添加到单击处理程序中。

$("#theSelect option[value=" + value + "]").removeAttr('disabled');

这将在您选择/删除这些选项时分别禁用/启用它们。

$("#theSelect").change(function(){
var value = $(this).val();
if (value === '') return;
var theDiv = $(".is" + value);


var option = $("option[value='" + value + "']", this);
option.attr("disabled","disabled");


theDiv.slideDown().removeClass("hidden");
theDiv.find('a').data("option",option);
});




$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
$(this).data("option").removeAttr('disabled');
});

演示: http://jsfiddle.net/AaXkd/

请试试这个,

$('#select_id option[value="'+value+'"]').attr("disabled", true);