【问题标题】:Enable all text fields but not the file field启用所有文本字段,但不启用文件字段
【发布时间】:2014-10-11 07:24:41
【问题描述】:

我正在尝试启用我在此函数中调用的每个文本字段,但我不想启用 type="file" 字段。发生的情况是 type="file" 字段无论如何都被启用了。我错过了什么吗?

function disabled_fields(fields, state) {
    if(state == true) {
        $(fields).each(function() {
            $(this).attr('disabled', true);
        });
    } else {
        if(state == false) {
            $(fields).each(function() {
                if($(this).attr('type') != 'file') {
                    $(this).attr('disabled', false);
                }
            });
        }
    }
};

// Runs like this
disabled_fields('input, textarea', false);

【问题讨论】:

  • 如果你尝试.prop("disable", true) 会发生什么?还有一点注意:你不必检查状态,你可以直接将状态设置为truefalse
  • 添加一个小提琴,让它变得更好。

标签: jquery each disabled-input


【解决方案1】:

您可以使用.not() 排除元素,

function disabled_fields(state) {
    $("input,textarea").not("[type='file']").prop("disabled", state);
}

还要注意,您不必遍历每个元素来设置 disabled 属性。

【讨论】:

  • 该死的,忍者我 :p 你也可以像这样缩短它.not(':file')
【解决方案2】:

试试这个代码,

function disabled_fields(fields, state) {
    if (state == true) {
        $(fields).each(function () {
            $(this).attr('disabled', true);
        });
    } else if (state == false) {
        $(fields).not("[type='file']").each(function () {
            $(this).attr('disabled', false);
        });
    }
};

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 2019-10-25
    • 1970-01-01
    • 2022-01-03
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多