未輸入時屬性value的默認值--js學習之路" type="hidden"/>

未輸入時屬性value的默認值--js學習之路


在百度ife刷題是自己的一個錯誤引發了我對<input type="text"/>的學習。

先貼代碼:

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>example</title>
  </head>
<body>
  <label for="weather_input">請輸入北京今天空氣質量:<input id="weather_input" type="text"/></label>
  <button id="confirm_button">確認</button>
  <p>你輸入的值是:<span id="value_show">尚未輸入</span></p>
<script type="text/javascript">
window.onload=function(){
  var button=document.getElementById("confirm_button");
  var span=document.getElementById("value_show");
  var input=document.getElementById("weather_input").value;
  button.onclick=function(){
  span.innerHTML=input;
}
}
</script>
</body>
</html>

 

這段代碼語法上是正確的,不過邏輯上是有問題的:var input=document.getElementById("weather_input").value;該語句中input獲取了input輸入框的默認值,之后再觸發button.onclick時,input的值無法即時更新,也就無法達到程序即時顯示效果。

這引出了今天探討的問題:在<input type="text"/>中未規定value的初始值同時用戶未輸入時,value的默認值是什么?

null還是undefined還是""?

從var input=document.getElementById("weather_input").value看,我們可以看到document.getElementById("weather_input")這個元素節點對象是存在的,不為空,因此排除null。

至於到底是""還是undefined,我通過實踐找到了答案。

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>example</title>
  </head>
<body>
  <label for="weather_input">請輸入北京今天空氣質量:<input id="weather_input" type="text"/></label>
  <button id="confirm_button">確認</button>
  <p>你輸入的值是:<span id="value_show">尚未輸入</span></p>
<script type="text/javascript">
window.onload=function(){
  var button=document.getElementById("confirm_button");
  var span=document.getElementById("value_show");
  alert(document.getElementById("weather_input").value===undefined);//驗證是否等於undefined
  alert(document.getElementById("weather_input").value==="");//驗證是否等於""
}
}
</script>
</body>
</html>

 

通過上述代碼,我看到的程序運行結果是:第一個彈出框顯示為false;第二個彈出框顯示為true。

結論顯而易見:在<input type="text"/>中未規定value的初始值同時用戶未輸入時,value的默認值是""。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM