使用document.getElementById设置输入值不是真正设置值 [英] Setting input value using document.getElementById not truely setting the value
问题描述
我有一个输入:
<input type="text" class="input" name="email" id="email" value="" disabled>
和JavaScript:
And JavaScript:
$email = "stackemail@emails.com";
function setEmail(email) {
document.getElementById("email").value = email;
}
window.onload = setEmail($email);
现在,它确实在输入字段中显示了我想要的电子邮件:
Now, it does show the email in the input field just how i want it to:
但是当我检查元素时它没有设置值:
But it doesn't set the value when i inspect the element:
即使我更改了inspect元素中的值,它也会保留stackemail@emails.com
Even when i change the value inside the inspect element, it stays "stackemail@emails.com"
现在我需要的价值与显示的价值相同
为什么不这样做?
Now i need the value to be the same as what it is showing Why is it not doing so?
推荐答案
您正在更新它 value
DOM元素的属性,而不是它的值属性。要在标记中反映使用 setAttribute()
用于更新属性。
You are updating it value
property of the DOM element and not its value attribute. To reflect in the markup use setAttribute()
which is using to update an attribute.
function setEmail(email) {
document.getElementById("email").setAttribute('value', email);
}
$email = "stackemail@emails.com";
function setEmail(email) {
document.getElementById("email").setAttribute("value", email);
document.getElementById("email2").value = email;
}
window.onload = setEmail($email);
<input type="text" class="input" name="email" id="email" value="" disabled>
<input type="text" class="input" name="email" id="email2" value="" disabled>
这篇关于使用document.getElementById设置输入值不是真正设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!