如何将用户输入保存到 HTML 和 JavaScript 中的变量中 [英] How to save user input into a variable in HTML and JavaScript

查看:41
本文介绍了如何将用户输入保存到 HTML 和 JavaScript 中的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个游戏,一开始它会询问你的名字,我希望这个名字被保存为变量.

这是我的 HTML 代码:

I am making a game and at the start it asks for your name, I want this name to be saved as variable.

Here is my HTML code:

<form id="form" onsubmit="return false;">
<input   style=position:absolute;top:80%;left:5%;width:40%; type="text" id="userInput">
<input   style=position:absolute;top:50%;left:5%;width:40%; type="submit"    onclick="name()">
</form>

这是我的 JavaScript 代码

And here is my JavaScript Code

function name()
{
var input = document.getElementById("userInput");
alert(input);
}

推荐答案

它不起作用,因为 name 是 JavaScript 中的保留字.将函数名称更改为其他名称.

It doesn't work because name is a reserved word in JavaScript. Change the function name to something else.

参见 http://www.quackit.com/javascript/javascript_reserved_words.cfm

<form id="form" onsubmit="return false;">
    <input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
    <input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>

function othername() {
    var input = document.getElementById("userInput").value;
    alert(input);
}

这篇关于如何将用户输入保存到 HTML 和 JavaScript 中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆