使用document.getElementById设置输入值未真正设置值

Jel*_*lle 1 html javascript jquery

我有一个输入:

<input type="text" class="input" name="email" id="email" value="" disabled>
Run Code Online (Sandbox Code Playgroud)

和JavaScript:

$email = "stackemail@emails.com";

function setEmail(email) {
        document.getElementById("email").value = email;
    }

    window.onload = setEmail($email);
Run Code Online (Sandbox Code Playgroud)

现在,它确实在输入字段中显示电子邮件,我希望它如何: 它确实显示stackemail@emails.com

但是当我检查元素时,它没有设置值: 值=“”

即使我更改了inspect元素内的值,它仍然保持为“ stackemail@emails.com”

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

Pra*_*lan 5

您正在更新valueDOM元素的it 属性,而不是其value属性。为了反映在标记中,该标记用于setAttribute()更新属性。

function setEmail(email) {
   document.getElementById("email").setAttribute('value', email);
}
Run Code Online (Sandbox Code Playgroud)

function setEmail(email) {
   document.getElementById("email").setAttribute('value', email);
}
Run Code Online (Sandbox Code Playgroud)
$email = "stackemail@emails.com";

function setEmail(email) {
  document.getElementById("email").setAttribute("value", email);
  document.getElementById("email2").value = email;
}

window.onload = setEmail($email);
Run Code Online (Sandbox Code Playgroud)

  • 摆弄两个要打印的元素(如果需要):https://jsfiddle.net/evhzofz2/1/(同时使用`setAttribute`和`value`) (2认同)