javascript - 有没有办法接受用户输入并将其转换为 JS 的变量?
问题描述
我目前有一个网页,我希望用户能够输入他们的姓名和年龄。完成后,他们点击提交,第一个输入设置为 var name,第二个输入框设置为 var age。这可能吗?
这是我尝试过的
<form>
<input type="text" Name:"firstname"><br>
<input type="text" Age:"age"><br>
<input type="submit" value="Done">
</form>
但是,我不确定如何将输入设置为值。
解决方案
首先 - 您的 HTML 标记不正确。我真诚地建议您阅读此内容。
https://www.w3schools.com/html/default.asp 和 https://www.w3schools.com/js/default.asp 或您选择的任何其他网站。
其次 - 一旦你更正了你的标记 - 你可以这样做:
<input type="text" id="firstname">
<input type="text" id="age">
<input type="button" id="submit" value="Set The Variables">
<script>
//Get the dom element you want to listen to and attach a click event
document.getElementById("submit").addEventListener("click", setVars);
function setVars(){
//Set the variables
var firstname = document.getElementById("firstname").value;
alert ("Vars Set :" + firstname);
}
</script>
推荐阅读
- javascript - JavaScript中函数输出的问题
- python - Errno 2:没有这样的文件或目录:'C:\\tmp\\cat.log'
- django - 如何从类中返回 JsonResponse?
- python - 使用itertools库从python中的30个元素中选择11个元素时如何修复内存错误?
- java - java - 如何使用RestFull webservice打印请求中的属性以响应java?
- r - 如何使用数据框制作直方图
- java - Java - 如何配置 LDAP 身份验证?
- python - 如何在训练/验证/测试中对齐 pandas get_dummies?
- ios - 使用 webrtc iOS swift 在视频通话期间纠正 iPhoneX 上的远程视频大小
- javascript - 如何使用 redux-saga 缓冲操作