$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);

其他回答

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

$.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();

禁用:

$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.

启用:

$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.

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

方法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>

禁用输入字段的另一种方法是使用jQuery和css,如下所示:

jQuery("#inputFieldId").css({"pointer-events":"none"})

并且为了实现相同的输入,代码如下:

jQuery("#inputFieldId").css({"pointer-events":""})