$input.disabled = true;

or

$input.disabled = "disabled";

哪一种是标准方式?相反,如何启用禁用的输入?


当前回答

2018年更新:

现在不需要jQuery了,因为document.querySelector或document.querySelectedAll(对于多个元素)做的工作与$几乎完全相同,加上更明确的getElementById、getElementsByClassName、getElementByTagName

禁用“输入复选框”类的一个字段

document.querySelector('.input-checkbox').disabled = true;

或多个元素

document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);

其他回答

有许多方法可以使用它们来启用/禁用任何元素:

方法1

$("#txtName").attr("disabled", true);

方法2

$("#txtName").attr("disabled", "disabled");

如果使用jQuery 1.7或更高版本,请使用prop(),而不是attr()。

$("#txtName").prop("disabled", "disabled");

如果您希望启用任何元素,则只需执行与禁用该元素相反的操作即可。然而,jQuery提供了另一种删除任何属性的方法。

方法1

$("#txtName").attr("disabled", false);

方法2

$("#txtName").attr("disabled", "");

方法3

$("#txtName").removeAttr("disabled");

同样,如果使用jQuery 1.7或更高版本,请使用prop(),而不是attr()。这就是使用jQuery启用或禁用任何元素的方式。

<html>
<body>

Name: <input type="text" id="myText">



<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>

<script>
function disable() {
    document.getElementById("myText").disabled = true;
}
function enable() {
    document.getElementById("myText").disabled = false;
}
</script>

</body>
</html>

2018,无JQuery(ES6)

禁用所有输入:

[...document.querySelectorAll('input')].map(e => e.disabled = true);

禁用id=“my input”的输入

document.getElementById('my-input').disabled = true;

问题是JQuery,它只是仅供参考。

我使用@gnarf答案并将其添加为函数

   $.fn.disabled = function (isDisabled) {
     if (isDisabled) {
       this.attr('disabled', 'disabled');
     } else {
       this.removeAttr('disabled');
     }
   };

然后像这样使用

$('#myElement').disable(true);

您可以将其放在代码中的全局位置:

$.prototype.enable = function () {
    $.each(this, function (index, el) {
        $(el).removeAttr('disabled');
    });
}

$.prototype.disable = function () {
    $.each(this, function (index, el) {
        $(el).attr('disabled', 'disabled');
    });
}

然后你可以写一些东西,比如:

$(".myInputs").enable();
$("#otherInput").disable();