简体   繁体   English

如何显示输入值?

[英]How can I display the input value?

I would like to show what I write in the input, but everytime I try the alert window shows "undefined".我想显示我在输入中写的内容,但每次我尝试警报 window 时都会显示“未定义”。 This is the code.这是代码。 Thanks.谢谢。

<body>
    <input id="input"></input>
    <button id="search">search</button>
   
    <script>
        document.getElementById('search').addEventListener("click", show);
        var input = getElementById('input');
        var search = input.value;
        function show() {
          alert(search);
        }
    </script>
</body>

you must bring var search into show function declaration in order to get new value of search box every time the event occurs.您必须将var search带入show function 声明中,以便在每次事件发生时获取搜索框的新值。

function show(){
  var search = input.value;
  alert(search);
}

First you need to use document.getElementById instead of just getElementById .首先,您需要使用document.getElementById而不仅仅是getElementById Then you need to put var search = input.value inside the show function so that it gets the current value each time you want to show it, and not just the initial one.然后你需要把var search = input.value放在show function 里面,这样每次你想显示它时它都会得到当前值,而不仅仅是初始值。

 document.getElementById('search').addEventListener("click", show); var input = document.getElementById('input'); function show() { var search = input.value; alert(search); }
 <input id="input"></input> <button id="search">search</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM