0

我有以下代码通过使用 removeAttr 函数删除 disabled 属性来解锁下拉列表。此示例在 Mozilla Firefox 24 for Ubuntu 中不起作用。但是,如果在 RemoveAttr 函数之后添加一个警报,它可以正常工作,如下一个示例所示:

        $("#dropdown1").change(function() {
        $('#dropdown2').find('option').remove().end();
        if (obj[$(this).val()] !== undefined)
        {

            $('#dropdown2').removeAttr('disabled');
            $('#dropdown2').append('<option></option>' + obj[$(this).val()]);
            $('#dropdown2').attr('required', true);
        }
        else
        {
            $('#dropdown2').attr('disabled', true);
            $('#dropdown2').attr('required', false);
        }

    });

工作示例:

        $("#dropdown1").change(function() {
        $('#dropdown2').find('option').remove().end();
        if (obj[$(this).val()] !== undefined)
        {

            $('#dropdown2').removeAttr('disabled');
            alert("REMOVED");
            $('#dropdown2').append('<option></option>' + obj[$(this).val()]);
            $('#dropdown2').attr('required', true);
        }
        else
        {
            $('#dropdown2').attr('disabled', true);
            $('#dropdown2').attr('required', false);
        }

    });

.prop 的示例也不起作用:

        $("#dropdown1").change(function() {
        $('#dropdown2').find('option').remove().end();
        if (obj[$(this).val()] !== undefined)
        {
            $('#dropdown2').prop('disabled', false);
            $('#dropdown2').append('<option></option>' + obj[$(this).val()]);
            $('#dropdown2').attr('required', true);

        }
        else
        {
            $('#dropdown2').prop('disabled', true);
            $('#dropdown2').attr('required', false);
        }

    });
4

3 回答 3

4

您应该使用.prop()设置禁用的属性状态

启用

$('#dropdown2').prop('disabled', false);

禁用

$('#dropdown2').prop('disabled', true);

阅读:属性与属性

于 2013-09-26T13:48:15.930 回答
3

从(文档)(http://api.jquery.com/attr/#entry-longdesc):

从 jQuery 1.6 开始,.attr() 方法为尚未设置的属性返回 undefined。要检索和更改 DOM 属性,例如表单元素的选中、选择或禁用状态,请使用 .prop() 方法。

所以你应该改用.prop()函数。

$('#dropdown2').prop('disabled', false); // Enables the element
$('#dropdown2').prop('disabled', true ); // Disables the element
于 2013-09-26T13:48:27.753 回答
1

使用道具

$('#dropdown2').prop('disabled', false);

disable true 禁用元素并禁用 false 启用元素

于 2013-09-26T13:49:42.453 回答