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

在百度ife刷題是本身的一個錯誤引起了我對<input type="text"/>的學習。javascript

先貼代碼:html

 

<!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的值沒法即時更新,也就沒法達到程序即時顯示效果。java

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

null仍是undefined仍是""?spa

從var input=document.getElementById("weather_input").value看,咱們能夠看到document.getElementById("weather_input")這個元素節點對象是存在的,不爲空,所以排除null。code

至於究竟是""仍是undefined,我經過實踐找到了答案。htm

 

<!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的默認值是""。blog

相關文章
相關標籤/搜索