zoukankan      html  css  js  c++  java
  • <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的默认值是""。

  • 相关阅读:
    Part0:安装Django
    计算机技术与科学系列笔记
    svg基础知识体系建立
    js如何判断字符串里面是否含有某个字符串
    js字符串如何倒序
    js判断值是否是数字
    HTML DOM 知识点整理(一)—— Document对象
    Git hub pull时候的错误 : The current branch is not configured for pull No value for key branch.master.merge found in configuration
    Map的3种遍历[轉]
    如何刪除GitHub中的repository
  • 原文地址:https://www.cnblogs.com/mingjiezhang/p/5371224.html
Copyright © 2011-2022 走看看