0

我试图将这两个代码想法绑定在一起,但它不起作用。

我想在选择后禁用第一个选项。

这是我想要的行为;做出选择后,第一个选项被禁用。

是我的代码,我希望在选择后续元素时禁用第一个选项。

4

2 回答 2

1

[更新答案]

http://jsfiddle.net/N9JEx/2/

function displayVals() {
    var singleValues = $("select option:selected").text();
    if (!isNaN(singleValues )) {
        $("#hiddenselect").val(singleValues);
        $("<p></p>").html("Percent of : &nbsp" + singleValues).appendTo('body');
    }
}

$(document).ready(function() {
    $("select").change(function() {
        displayVals();
        if (this.selectedIndex > 0) {
            var option = $('option:selected', this);
            option.prop('disabled', true);
        }
    });
});​
于 2012-05-17T20:19:52.497 回答
1

我相信这回答了您的询问:

http://jsfiddle.net/dq97z/66/

在里面displayVals我执行了以下操作:

if ($("#menucompare").prop("selectedIndex") !== "0") {
    // Within the select (you could be more specific) find
    // the first (direct descendant) option value and 
    // disable it to make it unselectable
    $("select > option:first").prop("disabled", "disabled")
}

此段找出您的选择菜单的选定索引是什么,如果用户选择了除初始索引 (0) 以外的其他内容,它将第一个选项设置为禁用。

更新:http: //jsfiddle.net/dq97z/72/

根据文档和@silkster 的建议禁用时更改attr()为。谢谢prop()

此外,如果您不希望在开始时选择该选项,您甚至可以在没有 if 语句的情况下执行此操作,如此处所示

function displayVals() {
    var singleValues = $("select option:selected").text();
    ....
    $("select > option:first").prop("disabled", "disabled")
}

加载 DOM 后发生禁用(第一个禁用),因此选择仍然可以选择“请选择”。哇...这是很多“选择”。

如果您想将 if 语句保留在那里(这意味着“选择一个”是可选择的,直到实际选择另一个),您的 if 语句需要是这样的:

if ($("#menucompare").prop("selectedIndex") !== 0) // with no quotes around zero
于 2012-05-17T20:31:18.017 回答