我有一个输入:
<input type="text" class="input" name="email" id="email" value="" disabled>
和JavaScript:
$email = "stackemail@emails.com";
function setEmail(email) {
document.getElementById("email").value = email;
}
window.onload = setEmail($email);
即使我更改了inspect元素中的值,它仍保持“stackemail@emails.com”
现在我需要将值与显示的值相同 为什么不这样做?
答案 0 :(得分:5)
您正在更新DOM元素的value
属性,而不是其value属性。要在标记中反映使用setAttribute()
来更新属性。
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>
答案 1 :(得分:1)
无论如何工作......检查员没有显示你的更改,如果你想尝试使用setAttribute函数但工作正常
$email = "stackemail@emails.com";
function setEmail(email) {
document.getElementById("email").value = email;
//if u want change attr.. try works too
//document.getElementById("email").setAttribute('value',email);
}
function getEmail(){
return document.getElementById("email").value;
}
document.addEventListener("DOMContentLoaded", function(event) {
setEmail($email);
console.log('value: ' + getEmail());
});
<input type="text" class="input" name="email" id="email" value="" disabled />
答案 2 :(得分:0)
window.onload = setEmail($email);
SetEmail将立即执行 。你想要
window.onload = ()=>setEmail($email);
或旧浏览器
window.onload =function(){
setEmail($email);
};