gpt4 book ai didi

javascript - 输入值将保存在哪里?

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:27 25 4
gpt4 key购买 nike

假设我们有以下 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 没有关于它的任何信息?

最佳答案

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

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

而输入的“值”属性仅表示其默认值:

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

请记住,即使用户在输入中输入任何文本,也不会更新输入的值属性。尝试在下面代码段的输入中输入文本,注意 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">

关于javascript - 输入值将保存在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com