• <input type="text"/>未输入时属性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的默认值是""。

  • 相关阅读:
    删除指定字符
    Palindromes&nbsp;_easy&nbsp;version
    统计元音
    查找最大元素
    首字母变大写
    Intent加强
    GUI_键盘事件
    GUI_鼠标事件
    GUI_事件监听机制与ActionListener演示
    GUI概述与Frame演示
  • 原文地址:https://www.cnblogs.com/mingjiezhang/p/5371224.html
Copyright © 2020-2023  润新知