【问题标题】:Why does setting the "disabled" property to false also remove the "disabled" attribute?为什么将“禁用”属性设置为 false 也会删除“禁用”属性?
【发布时间】:2014-06-20 20:39:56
【问题描述】:

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

<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 源代码中被禁用?

【问题讨论】:

  • 它删除了该属性,因为按钮在未禁用时不再具有禁用属性。如果需要,某些属性确实会更改属性。

标签: javascript html forms dom


【解决方案1】:

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

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

它可以用作property (Example):

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,是你要求的吗?

【讨论】:

  • 我的意思是设置属性不应该影响属性。见这里:jsfiddle.net/bKGLk
  • 不,我不想更改来源。我想检索源中的值。它适用于value 属性,但不适用于disabled 属性。
【解决方案2】:

.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) {
    …
}

【讨论】:

  • 如果它通过 javascript 被禁用,你可以通过检查源代码来检查它是否已经被禁用(not 使用 Firebug/其他开发工具,而当你出现按 F12,而不是使用 Ctrl+U,从服务器接收到的实际页面)。
  • @xFortyFourx:他们正在讨论代码中的运行时检查。
  • @cookiemonster 好的,谢谢。我没有看到 OP 这么问。
  • 这太愚蠢了。为什么不能像 &lt;input value="…"&gt; 那样设置属性不会影响属性,例如jsfiddle.net/bKGLk?如果真的没有办法从 HTML 源代码(使用标准 API)中检索原始禁用状态,那真是太愚蠢了。
  • @ŠimeVidas:更有趣的是,对于button 元素,更改.value 属性确实 会更新"value" 属性,这与input 不同元素。 jsfiddle.net/Rhj3c/5
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2011-11-23
  • 2012-08-13
  • 1970-01-01
  • 2017-11-05
  • 2011-08-04
  • 1970-01-01
相关资源
最近更新 更多