简体   繁体   English

从用户获取HTML输入

[英]Get HTML input from user

I'm making a game and I've a html text box, <form> <input> </form> where the users will type in a number and submit it using a html button <button> . 我正在做一个游戏,我有一个HTML文本框<form> <input> </form> ,用户可以在其中输入数字并使用html按钮<button>提交。 How do I get the number using JavaScript so I can use it in my game.js so I'll know how many lives the user want when the submit button is pressed? 如何使用JavaScript获取数字,以便可以在game.js使用它,以便在按下“提交”按钮时知道用户想要多少生命?

I'm not quite sure if this is the correct approach but I was thinking getting the id of the <input> tag and then for the JavaScript part I would use .getElementById of some sort? 我不太清楚,如果这是正确的做法,但我想获取id的的<input>标签,然后JavaScript的一部分,我会用.getElementById某种? However, I'm not sure how to incorporate the submit button so that only when it's pressed, I will receive what the user inputted. 但是,我不确定如何合并“提交”按钮,以便仅在按下该按钮时,我才能收到用户输入的内容。

Or is there another better way to do this? 还是有另一种更好的方法来做到这一点? And if possible, can you provide an example of the codes for doing this? 并且,如果可能的话,您可以提供执行此操作的代码示例吗?

Let me know if any clarification is needed, thanks! 让我知道是否需要澄清,谢谢!

There are multiple ways to do what you are asking for, one way to do it is as cristian has shown in the comment(using jquery). 有多种方法可以满足您的要求,一种方法就是cristian在注释中显示(使用jquery)。

In this jsfiddle page I've shown a sample way to do it just using javascript. 在这个jsfiddle页面中,我展示了一个仅使用JavaScript的示例方法。

The code used in the page is as shown below: 页面中使用的代码如下所示:

document.getElementById("submit").onclick = function(){
    var a = document.getElementById("input").value;
    alert("The entered value is: "+a);
}

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

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