[英]not able to get user input in javascript from html
我知道我应该使用document.getelemtbyID
但由于某种原因它对我不起作用。 我正在尝试构建一个简单的剪刀石头布游戏,其中我有一个石头剪刀布 class 和一个index.js
,我必须将用户名作为 function 传递给我的 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 无法正常工作。
这是我的 Javascript 代码 -
const userName = document.getElementById(`username`).value;
然后我将它传递给 class -
let game=new RockPaperScissors(userName)
game.play(userName); (which is a function in the class)
这是我的 HTML 用于输入用户名 -
<div id="welcome-screen">
<form id="name-form">
<div class="form-group">
<label for="username">Your name</label>
<input type="text" id="username" class="form-control"
name="username" placeholder="Enter Name Here...">
<button type="button" id="start-game-button"
class="btn btn-primary">Start Game!</button>
</div>
</form>
我尝试了几种方法能够在我的 javascript 中登录用户名,但它不起作用,我尝试在控制台中登录它,但我仍然没有看到结果。
尝试将type=submit
添加到按钮。
<button type="submit" id="start-game-button" class="btn btn-primary">Start Game!</button>
这是答案
About your above code: there is no pre-defined method of click event in the core javascript, so i have created one function in javascript and just called it on button onclick event.
您的代码只是获得了文本框的值,但没有触发事件来获取文本框的值。
var name = ""; function getname() { name = document.getElementById(`username`).value; alert(name); }
<div id="welcome-screen"> <form id="name-form"> <div class="form-group"> <label for="username">Your name</label> <input type="text" id="username" class="form-control" name="username" placeholder="Enter Name Here..."> <button type="button" onclick="getname()" id="start-game-button" class="btn btn-primary">Start Game!</button> </div> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.