2013-03-09 140 views
5

我想在那里有一个我的屏幕上的文本框(就像我现在输入的那个),你可以输入,然后点击一个提交按钮,它会发送你在框中键入的任何内容到javascript和JavaScript打印出来。这是我的代码这是工作的部分。Javascript - 用户通过HTML输入标签输入来设置一个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> 

OK所以这是很好的,但可以说,我想从文本框和按钮输入,同时我在一个功能就是已经不希望重新启动功能?

感谢, 杰克

+6

我真的不明白你在谈论你最后一句话是什么。我的意思是。你**已经在一个功能**和**不想重新启动**。这是什么意思? – kidwon 2013-03-09 00:12:31

+0

因此,如果我想用它启动一个函数,那么我的代码就可以工作,但是我希望提交按钮在一个函数已经运行的时候实质上工作。我会添加到按钮来做到这一点的属性?当前启动“test()”函数将不起作用,因为我不想启动该功能。 – user1836262 2013-03-09 00:15:14

+1

你的意思是你想要一个循环等待输入的函数吗?这不能在JavaScript中工作。除此之外,您可以随时随地使用'document.getElementById(“userInput”).value'。 – Dave 2013-03-09 00:20:16

回答

9

脚本运行时,它会阻止页面执行任何操作。您可以解决这两种方法之一:

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

谢谢,我会把它分成2个功能 – user1836262 2013-03-09 00:30:04

4

这是坏的风格,但我会假设你有一个很好的理由这样做类似的东西。

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

为什么它的风格不好? – user1836262 2013-03-09 17:58:55

+0

当它是事件驱动的时候,Javascript的效果最好,而不是一个单一的全部循环。如果事情按特定顺序发生并且您没有其他方式执行该操作,那么您只应该这样做。 – Dave 2013-03-09 18:26:57

2

晚读这篇文章,但.. 我看了你的问题的样子,你只需要改变两行代码:

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

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