输入值将保存在哪里?

Where input value will be saved?

假设我们有以下 HTML:

<div class="form-group">
    <label class="col-md-3 col-xs-3 col-sm-3 control-label">Phone</label>
    <div class="col-md-4 col-xs-4 col-sm-4">                   
        <input id="input_id" type="tel" required="" pattern="^\d{10}$"> 
    </div>
</div>

好像input没有属性value,但是如果我执行

document.querySelector('#input_id').value;
document.querySelector('#input_id').defaultValue;

我会得到:

""
""

作为输出。然后,如果我在输入字段中键入 123 并再执行一次:

document.querySelector('#input_id').value;
document.querySelector('#input_id').defaultValue;

输出将是:

"123"
""

此示例表示 input 字段有一个属性 value。问题是:

这个值(默认值和当前值)存储在哪里,因为 HTML 没有关于它的任何信息?

存储在 属性 个 DOM 元素对象中。默认情况下,如果你写:

<input id="input_id" type="tel" required="" pattern="^\d{10}$"> 

然后就像

<input id="input_id" type="tel" required="" pattern="^\d{10}$" value="">

如果您将值写为 value="123",则值和默认值属性会相应更改。

DOM 元素的任何数据都存储在该选项卡的浏览器内存中,由浏览器自行管理。由于您的 Javascript 只是该内存的一部分,因此它以某种方式存储在那里。所有工作原理的实际细节都隐藏在浏览器中,并且浏览器之间可能有所不同。

输入的值是其内部状态。它可能等于也可能不等于输入元素上的值属性。

A control’s value is its internal state. As such, it might not match the user’s current input.

For instance, if a user enters the word "three" into a numeric field that expects digits, the user’s input would be the string "three" but the control’s value would remain unchanged. Or, if a user enters the email address " awesome@example.com" (with leading whitespace) into an email field, the user’s input would be the string " awesome@example.com" but the browser’s UI for email fields might translate that into a value of "awesome@example.com" (without the leading whitespace).

https://www.w3.org/TR/html51/sec-forms.html#forms-value

而输入上的 "value" 属性仅表示其默认值:

The value content attribute gives the default value of the input element. When the value content attribute is added, set, or removed, if the control’s dirty value flag is false, the user agent must set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, and then run the current value sanitization algorithm, if one is defined.

https://www.w3.org/TR/html51/sec-forms.html#element-attrdef-input-value

请记住,即使用户在输入中输入任何文本,也不会更新输入的值属性。尝试在下面代码段的输入中输入文本,注意值属性没有更新:

setInterval(function() {
  console.clear();
  console.log("Attribute: ", $("input").attr("value"));
  console.log("Value: ", $("input").val());
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input value="default">