【问题标题】:<input> has no value in HTML but does in JavaScript? [duplicate]<input> 在 HTML 中没有价值,但在 JavaScript 中有价值? [复制]
【发布时间】:2021-11-07 23:52:28
【问题描述】:

我在页面上找到了一个&lt;input type="text" ... 元素,$('thatElement').val()$('thatElement')[0].value 返回值,该值显示在渲染输出中,但元素本身没有value="..." 属性。

一个输入元素的HTML中怎么可能没有value属性,但它仍然有值并且仍然显示它的值?

浏览器控制台:


> $('thatElement')[0].value
'The text that the page shows inside of the input'
> $('thatElement')[0].outerHTML
'<input autocomplete="off" type="text" readonly spellcheck="false">'

【问题讨论】:

  • 取决于您的比较方式。您是否有机会比较页面源代码(不是通过任何浏览器中的开发工具)和 JS 评估?因为源代码(通过右键单击 -> 显示源代码)只会显示最初来自服务器的内容,从那时起很可能已经更改了。
  • @ArSeN 检查元素,甚至.outerHTML 显示没有值属性
  • Attributes are not the same as properties。该属性仅显示初始值并且(通常)永远不会改变。该属性具有当前值,但不显示在 HTML 中。

标签: javascript html dom


【解决方案1】:

文档的来源和它的 DOM 表示是有区别的。源文件是静态的,不会更改。 DOM 可能会改变。我认为这取决于你如何操作它。

在此示例中,输入值已设置但 DOM 未更新:(运行并检查结果)

document.querySelector('input').value = 42;
&lt;input /&gt;

在这个例子中,输入和 DOM 都被更新了:

document.querySelector('input').setAttribute('value', 'foobar');
&lt;input /&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    相关资源
    最近更新 更多