为什么设置"禁用" property to false也删除" disabled"属性?

时间:2014-05-04 14:23:24

标签: javascript html forms dom

我有一个最初禁用的按钮:

<button disabled="disabled">Lorem ipsum</button>

对于此按钮,button.getAttribute('disabled')会返回"disabled"。但是,当我使用JavaScript启用此按钮时:

button.disabled = false;

然后button.getAttribute('disabled')开始返回null

现场演示: http://jsfiddle.net/Rhj3c/1/

为什么?不应该.getAttribute()返回原始HTML源代码中的值吗?然后,我如何确定原始HTML源代码中是否禁用了该按钮?

2 个答案:

答案 0 :(得分:5)

  

.getAttribute()不应该返回原始HTML源代码中的值吗?

不,按照the specification(强调我的):

  

如果反映的IDL​​属性是boolean属性,那么获取IDL属性必须在设置内容属性时返回true,如果不存在则返回false。在设置时,如果IDL属性设置为false ,则必须删除content属性,如果IDL属性设置为true,则必须将其设置为空字符串。 (这对应于boolean content attributes的规则。)

  

如何确定原始HTML源代码中是否禁用了该按钮?

在更改之前检查它。如果问题实际上仅限于“原始HTML源代码”而不是“元素最初是什么”(例如,如果它是用JavaScript创建的),那可能只是一个:

var originallyDisabled = Array.prototype.slice.call(
    document.querySelectorAll('[disabled]')
);
⋮
if (originallyDisabled.indexOf(button) !== -1) {
    …
}

答案 1 :(得分:1)

disabled属性是一个Boolean属性,如果存在,则指定该元素应该被禁用,如果不存在则启用该元素,它可以用作:

<!-- Disabled -->
<button disabled>Lorem ipsum</button>

它可以用作propertyExample):

var button = document.querySelector('button');
console.log(button.disabled); // true if present, false if not

// Or this
console.log(button.hasAttribute('disabled')); // true if present false if not

更新(Example):

var input = document.querySelector('input');
input.value = 'Dynamic value';
console.log(input.getAttribute('value')); // "Initial value" attribute is in source
console.log(input.value); // "Dynamic value" property is in ram, rendered on the screen

使用input.value设置ram中的属性而不是source,您需要使用setAttribute来更改source,这是您要求的吗?

相关问题