未输入时属性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

相关文章
相关标签/搜索