$input.disabled = true;

or

$input.disabled = "disabled";

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


当前回答

禁用:

$('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.

其他回答

$("input")[0].disabled = true;

or

$("input")[0].disabled = false;

2018年更新:

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

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

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

或多个元素

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

只是为了新的惯例,并使其适应未来(除非ECMA6(????)发生了巨大变化):

$(document).on('event_name', '#your_id', function() {
    $(this).removeAttr('disabled');
});

and

$(document).off('event_name', '#your_id', function() {
    $(this).attr('disabled','disabled');   
});

像这样使用,

 $( "#id" ).prop( "disabled", true );

 $( "#id" ).prop( "disabled", false );

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

方法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启用或禁用任何元素的方式。