Javascript 为什么要设置;残疾人士;属性为false时,还应删除;残疾人士;属性
我有一个最初被禁用的按钮:Javascript 为什么要设置;残疾人士;属性为false时,还应删除;残疾人士;属性,javascript,html,forms,dom,Javascript,Html,Forms,Dom,我有一个最初被禁用的按钮: <button disabled="disabled">Lorem ipsum</button> 然后按钮。getAttribute('disabled')开始返回null 现场演示: 为什么呢?.getAttribute()不应该从原始HTML源代码返回值吗?然后如何确定按钮在原始HTML源代码中是否被禁用?禁用的属性是一个布尔属性,当存在时,它指定元素应被禁用,如果不存在,那么它将被启用,并且可以用作: <!-- Disabled
<button disabled="disabled">Lorem ipsum</button>
然后按钮。getAttribute('disabled')
开始返回null
现场演示:
为什么呢?
.getAttribute()
不应该从原始HTML源代码返回值吗?然后如何确定按钮在原始HTML源代码中是否被禁用?禁用的属性是一个布尔属性,当存在时,它指定元素应被禁用,如果不存在,那么它将被启用,并且可以用作:
<!-- Disabled -->
<button disabled>Lorem ipsum</button>
更新():
使用input.value
在ram
中设置属性,而不是在source
中设置属性,需要使用setAttribute
更改source
,这是您要求的吗
.getAttribute()
不应该从原始HTML源代码返回值吗
否,根据(我的重点):
如果反射IDL属性是布尔属性
属性,则在获取IDL属性时,如果设置了内容属性,则必须返回true;如果未设置内容属性,则必须返回false。设置时,如果IDL属性设置为false,则必须删除内容属性;如果IDL属性设置为true,则必须将内容属性设置为空字符串。(这与的规则相对应。)
然后如何确定按钮在原始HTML源代码中是否被禁用
在它改变之前检查它。如果问题真的局限于“原始HTML源代码”,而不是“元素的初始形式”(例如,如果它是用JavaScript创建的),那么这可能只是一个:
var originallyDisabled = Array.prototype.slice.call(
document.querySelectorAll('[disabled]')
);
⋮
if (originallyDisabled.indexOf(button) !== -1) {
…
}
它会删除该属性,因为按钮在未禁用时不能再具有禁用属性。如果需要,某些属性会更改属性。如果通过javascript禁用该属性,则可以通过检查源代码来检查该属性是否已被禁用(当按F12键时,不使用Firebug/其他开发工具,而是使用Ctrl+U,即从服务器接收到的实际页面)@xFortyFourx:他们说的是代码中的运行时检查。@Cookie Monster啊,好的,谢谢。我没看到OP问这个,那太愚蠢了。为什么不能像
那样设置属性不影响属性,例如?如果真的无法从HTML源代码(使用标准API)检索原始禁用状态,那就太愚蠢了。@ŠimeVidas:更有趣的是,对于按钮元素,更改.value
属性确实会更新的“value”
属性,这与输入元素不同。我的观点是设置属性不应该影响属性。看这里:不,我不想改变来源。我想从源中检索该值。它适用于值
属性,但不适用于禁用的
属性。
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
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
var originallyDisabled = Array.prototype.slice.call(
document.querySelectorAll('[disabled]')
);
⋮
if (originallyDisabled.indexOf(button) !== -1) {
…
}