繁体   English   中英

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

[英]Javascript - User input through HTML input tag to set a Javascript variable?

我希望我的屏幕上有一个文本框(就像我现在正在键入的那个),你可以输入然后点击一个提交按钮,它会将你输入的任何内容发送到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>

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

谢谢,杰克

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

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

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

<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>

迟读这个,但..我读你的问题的方式,你只需要改变两行代码:

接受用户输入,功能写回屏幕。

<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>

<!-- add this line for function to write into -->
<p id="demo"></p>   

<script type="text/javascript">
function test(){
    var userInput = document.getElementById("userInput").value;
    document.getElementById("demo").innerHTML = userInput;
}
</script>

我试图将输入标签的值发送/添加到JavaScript变量中,这对我来说效果很好,这里是代码:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

暂无
暂无

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

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