您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

启用/禁用纯JavaScript中的按钮

启用/禁用纯JavaScript中的按钮

一个布尔属性,仅它的存在就会导致元素被禁用,无论该属性的值实际是多少。这就是为什么您可以通过将属性设置为来禁用JavaScript中的元素true的原因,您可以将其设置为任何值(这就是为什么将其设置为false禁用状态的原因)。

<input type="button" value="I'm disabled" disabled="true">

<input type="button" value="I'm disabled" disabled="false">

<input type="button" value="I'm disabled" disabled="doesn't matter">

<input type="button" value="I'm disabled" disabled="">

在HTML中,您甚至根本不需要为属性设置一个值:

<input type="button" value="I'm disabled" disabled>

但是,建议使用布尔属性的约定(如果您确实想为属性提供值),以便我们在开发人员之间具有一定的一致性,那就是将其值设置为等于属性名称本身。因此,要禁用JavaScript中的元素,请遵循建议的约定:

element.setAttribute("disabled", "disabled");

element.removeAttribute("disabled");



document.querySelector("input[type='button']").removeAttribute("disabled");


<input type="button" value="I'm NOT disabled" disabled="disabled">

现在,在JavaScript中使用DOM对象时,有两种方法可以影响 并且了解使用这两种技术的效果非常重要:

这可能会造成混淆,但是HTML状态是元素从外部看起来的样子,而属性状态是内部真正发生的事情,例如您可以戴上笑脸,以便看着您的人认为您很高兴( HTML状态),但实际上您可能对真实状态(属性状态)感到难过。

如果尚未设置属性状态,那么属性状态就很重要,并且将完全控制元素的状态。设置属性状态后,它会覆盖任何可能的属性状态,并控制元素的实际状态。

// Get a reference to the button

var btn = document.querySelector("[type=button]");



// Test what the current HTML state is:

console.log(btn.getAttribute("disabled"));



// Test what the current mapped property state is:

console.log(btn.disabled);



// Change the property state, which will override the HTML state and

// and cause it to become enabled.

btn.disabled = false;



// Test what the current HTML state is:

console.log(btn.getAttribute("disabled"));  // null because property overrode HTML



// Test what the current mapped property value is:

console.log(btn.disabled);


<input type="button" value="I'm disabled" disabled="disabled">

从 :

要启用该元素,请完全忽略此属性,而不是将值设置为false

javascript 2022/1/1 18:15:01 有658人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶