问题描述
假设我们有以下HTML:
Let's say we have following 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
,但是如果我执行
It seems like input
doesn't have attribute value
, but if I execute
document.querySelector('#input_id').value;
document.querySelector('#input_id').defaultValue;
我会得到:
""
""
作为输出.然后,如果我在输入字段 123
中输入并再次执行一次:
as output. Then if I type in input field 123
and execute one more time:
document.querySelector('#input_id').value;
document.querySelector('#input_id').defaultValue;
输出将是:
"123"
""
此示例表示 input
字段具有属性 value
.问题是:
This example means there is an attribute value
for an input
field. The question is:
此值(默认值和当前值)存储在何处,因为HTML对此没有任何信息?
Where this values(default and current) are stored, since HTML doesn't have any information about it?
推荐答案
输入的值是其内部状态.它可能等于或可能不等于输入元素上的value属性.
The value of an input is its internal state. It may or may not equal the value attribute on an input element.
例如,如果用户在需要数字的数字字段中输入单词三",则用户的输入将是字符串三",但控件的值将保持不变.或者,如果用户在电子邮件字段中输入电子邮件地址"[email protected]"(带有前导空格),则用户的输入将是字符串"[email protected]",但浏览器的电子邮件字段UI可能会将其翻译为变成"[email protected]"的值(不带前导空格).
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 " [email protected]" (with leading whitespace) into an email field, the user’s input would be the string " [email protected]" but the browser’s UI for email fields might translate that into a value of "[email protected]" (without the leading whitespace).
输入中的"value"属性仅表示其默认值:
Whereas the "value" attribute on an input merely represents its default value:
请记住,即使用户在输入中输入任何文本,也不会更新输入的value属性.尝试在下面的代码段中输入文本,然后注意value属性没有更新:
Keep in mind that even if the user enters any text into the input, it will not update the value attribute of the input. Try typing in text into the input in snippet below, and notice that the value attribute doesn't get updated:
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">
这篇关于输入值将保存在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!