gpt4 book ai didi

javascript - 使用 document.getElementById 设置输入值不是真正设置值

转载 作者:行者123 更新时间:2023-11-28 04:47:22 26 4
gpt4 key购买 nike

我有一个输入:

<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);

现在,它确实在输入字段中显示了我想要的电子邮件: it does show stackemail@emails.com

但是当我检查元素时它没有设置值: the value = ""

即使我更改了 inspect 元素中的值,它仍然是“stackemail@emails.com”

现在我需要的值与它显示的值相同为什么不这样做呢?

最佳答案

您正在更新 DOM 元素的 value 属性,而不是它的 value 属性。要反射(reflect)在标记中,请使用 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>

关于javascript - 使用 document.getElementById 设置输入值不是真正设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594068/

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