Javascript - 用户通过HTML输入标签输入来设置Javascript变量?

use*_*262 6 html javascript html5 user-input input

我希望我的屏幕上有一个文本框(就像我现在正在键入的那个),你可以输入然后点击一个提交按钮,它会将你输入的任何内容发送到javascript,然后javascript将它打印出来.这是我的代码这是有效的部分.

<html>
<body>
    <input type="text" id="userInput"=>give me input</input>
    <button onclick="test()">Submit</button>
    <script>
        function test()
        {
            var userInput = document.getElementById("userInput").value;
            document.write(userInput);
        }
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

好吧,这样很好,但是我可以说我想要从该文本框和按钮输入,而我已经在一个函数中并且不想重新启动该函数?

谢谢,杰克

Den*_*nis 11

当您的脚本运行时,它会阻止页面执行任何操作.您可以通过以下两种方法之一解决此问题:

  • 使用var foo = prompt("Give me input");,它将为您提供用户输入弹出框的字符串(或者null如果他们取消它)
  • 将代码拆分为两个函数 - 运行一个函数来设置用户界面,然后提供第二个函数作为在用户单击按钮时运行的回调.


Dav*_*ave 5

这是不好的风格,但我假设你有充分的理由做类似的事情。

<html>
<body>
    <input type="text" id="userInput">give me input</input>
    <button id="submitter">Submit</button>
    <div id="output"></div>
    <script>
        var didClickIt = false;
        document.getElementById("submitter").addEventListener("click",function(){
            // same as onclick, keeps the JS and HTML separate
            didClickIt = true;
        });

        setInterval(function(){
            // this is the closest you get to an infinite loop in JavaScript
            if( didClickIt ) {
                didClickIt = false;
                // document.write causes silly problems, do this instead (or better yet, use a library like jQuery to do this stuff for you)
                var o=document.getElementById("output"),v=document.getElementById("userInput").value;
                if(o.textContent!==undefined){
                    o.textContent=v;
                }else{
                    o.innerText=v;
                }
            }
        },500);
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)