簡體   English   中英

使用 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:

$email = "stackemail@emails.com";

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

    window.onload = setEmail($email);

現在,它確實在輸入字段中顯示了我想要的電子郵件: 它確實顯示了 stackemail@emails.com

但是當我檢查元素時它沒有設置值: 值 = ""

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

現在我需要該值與其顯示的值相同 為什么不這樣做?

您正在更新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> 

無論如何都可以...檢查器不會顯示您的更改,如果您想嘗試使用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 /> 

 window.onload = setEmail($email);

SetEmail 現在將執行。 你要

window.onload = ()=>setEmail($email);

或對於舊版瀏覽器

window.onload =function(){
   setEmail($email);
 };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM