$input.disabled = true;
or
$input.disabled = "disabled";
哪一种是标准方式?相反,如何启用禁用的输入?
$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);
其他回答
方法4(这是野生编码器答案的扩展)
txtName.disabled=1//0启用<input id=“txtName”>
您可以使用jQuery prop()方法动态禁用或启用表单元素或控件。prop()方法需要jQuery1.6及更高版本。
例子:
<script type="text/javascript">
$(document).ready(function(){
$('form input[type="submit"]').prop("disabled", true);
$(".agree").click(function(){
if($(this).prop("checked") == true){
$('form input[type="submit"]').prop("disabled", false);
}
else if($(this).prop("checked") == false){
$('form input[type="submit"]').prop("disabled", true);
}
});
});
</script>
只是为了新的惯例,并使其适应未来(除非ECMA6(????)发生了巨大变化):
$(document).on('event_name', '#your_id', function() {
$(this).removeAttr('disabled');
});
and
$(document).off('event_name', '#your_id', function() {
$(this).attr('disabled','disabled');
});
有许多方法可以使用它们来启用/禁用任何元素:
方法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>