简体   繁体   English

如何在单击事件的函数中运行用户输入?

[英]How Do I get the user input to be run in the function on click event?

I have gotten the code to semi work but when it does it creates an infinite loop. 我已经将代码编写为半工作但是当它执行时它会创建一个无限循环。

I tried comparing the datatype of the user input. 我尝试比较用户输入的数据类型。 I could not wrap my head around it conceptually so I am comparing numbers instead. 我无法在概念上绕过它,所以我正在比较数字。

HTML: HTML:

 let button = document.getElementById("button") var input = document.getElementById("number_of_souls").getElementById("takeinput").value let user_number = function() { for (let i = 1; i < 1; i++) { if (9000 <= input) { alert("Not many souls") } else 9000.1 >= input alert["That's over 9,000!"] } } button.addEventListener("click", user_number) 
 <div> <h1> How many Souls have you aquired? </h1> <form id="number_of_souls"> <input id="takeinput"> Souls <button id="button">submit</button> </form> </div> 

This is for a fan-page project in Darksouls. 这是Darksouls中的粉丝页面项目。 The question asked is "How many souls have you acquired? Once the user submits a number it should take the number and return an alert with "Not Many souls" or "That's over 9,000". 提出的问题是“你获得了多少灵魂?一旦用户提交了一个数字,它应该取数字并返回”不是很多灵魂“或”那超过9,000“的警报。

No need for the for loop, also you need to get the input value after clicking the button 不需要for循环,也需要在单击按钮后获取输入值

Also, add type="button" to your button to allow it to be clicked without submitting the form, if that's what you want 此外,在您的按钮上添加type="button" ,以便在不提交表单的情况下点击它,如果这是您想要的

 let button = document.getElementById("button") let user_number= function(){ var input = document.getElementById("takeinput").value if (input<=9000) alert("Not many souls") else alert("That's over 9,000!") } button.addEventListener("click", user_number) 
 <div> <h1> How many Souls have you aquired? </h1> <form id="number_of_souls"> <input id="takeinput"> Souls <button id="button" type="button">submit</button> </form> </div> 

Edit: As msanford said in the comments, the if/else there shows a little bit of an anomaly in javascript syntax. 编辑:正如msanford在评论中所说,if / else在javascript语法中显示出一点点异常。 Those statements are equivalent to: 这些陈述相当于:

if (input<=9000) {
  alert("Not many souls")
}
else {
  alert("That's over 9,000!")
}

As pointed out by other answers, the loop is not required, you can simply compare numbers. 正如其他答案所指出的那样,循环不是必需的,你可以简单地比较数字。 Also don't forget to convert a string value from the input to a number (eg by using parseInt before performing a comparison). 另外,不要忘记将字符串值从输入转换为数字(例如,在执行比较之前使用parseInt )。 Besides, unless you want a browser to submit the form, don't forget to call preventDefault on the fired event. 此外,除非您希望浏览器提交表单,否则不要忘记在已触发的事件上调用preventDefault

 const user_number = (e) => { e.preventDefault(); const value = parseInt(document.getElementById('takeinput').value, 10); const message = (9000 >= value) ? 'Not many souls' : 'Thats over 9,000!'; alert(message); } const button = document.getElementById('button'); button.addEventListener('click', user_number); 
 <div> <h1> How many Souls have you aquired? </h1> <form id="number_of_souls"> <input id="takeinput"> Souls <button id="button">submit</button> </form> </div> 

As a fan of dark soul series couldn't keep from participating :) 作为黑暗灵魂系列的粉丝无法参与:)

Because you're learning JavaScript, I'm going to take this opportunity to do a short code review, specifically of this block: 因为你正在学习JavaScript,所以我将借此机会进行简短的代码审查,特别是这个块:

for (let i = 1; i < 1; i++) {

    if (9000 <= input) {

      alert("Not many souls")
    } else 9000.1 >= input

    alert["That's over 9,000!"]
  }
  1. As others have said, no need for a for loop. 正如其他人所说,不需要for循环。
  2. The other syntax some have elegantly proposed is called a ternary operator ( ?: ) , which is also nice. 一些优雅提出的其他语法称为三元运算符( ?: :) ,这也很好。 In Python that's written more verbosely as print "Lots of souls!" if input >= 9000 else print "Not many souls" 在Python中,写得更详细,就像print "Lots of souls!" if input >= 9000 else print "Not many souls" print "Lots of souls!" if input >= 9000 else print "Not many souls" (whose only advantage over a regular if/else is that it can be written on a single line). print "Lots of souls!" if input >= 9000 else print "Not many souls" (其唯一优势在于常规if / else是它可以写​​在一行上)。
  3. Offsetting the numeric value you check for in if/else conditions is the wrong way to approach what ranges of values to include. 在if / else条件中偏移您检查的数值是错误的方法来接近要包括的值的范围。 The logic you want to apply is "Is what the user entered equal to over over 9000 or not ". 要应用的逻辑是“什么是用户输入等于完了完了9000 或不 ”。 So don't use >= and <= with a different number, use >= and < with the same number. 所以不要使用>=<=使用不同的数字,使用>=<使用相同的数字。
  4. That said, don't use any number; 也就是说,不要使用任何数字; an else is enough and captures the "or not" of your logical condition. 一个else就足够了,捕捉你的逻辑条件的“与否”。
  5. Your else 9000.1 >= input is not a condition, it means else {9000.1 >= input} , you probably meant else if (but see above - you don't need any condition). 你的else 9000.1 >= input不是一个条件,它意味着else {9000.1 >= input} ,你可能意味着else if (但见上文 - 你不需要任何条件)。
  6. Unlike Python, a block in JavaScript is surrounded by {} . 与Python不同,JavaScript中的{}包围。 While it is legal to write single-line if/else without braces if the code it runs is only a single statement , it's not idiomatic and almost always a bad idea. 如果编写单行if / else而没有大括号是合法的,如果它运行的代码只是一个语句 ,那么它不是惯用语,而且几乎总是一个坏主意。

Compare 相比

 const a = 1; if (a > 0) console.log("Higher than 0"); else console.log("Not higher than 0"); 

with

 const a = 1; if (a > 0) console.log("Higher than 0"); console.log("Another line"); else console.log("Not higher than 0"); 

That second one doesn't work. 第二个不起作用。 Get used to putting braces around blocks from the start, so that you don't forget to add them when you add more code. 习惯于从一开始就在块周围放置大括号,这样您就不会忘记在添加更多代码时添加它们。

  1. alert["That's over 9,000!"] ? alert["That's over 9,000!"] You mean alert() . 你的意思是alert() alert["That's over 9,000!"] looks for a key on a global variable alert called That's over 9,000! alert["That's over 9,000!"]在一个名为That's over 9,000!的全局变量alert上寻找一个键That's over 9,000! and doesn't call a function. 而且不会调用函数。
  2. On that note, don't use alert() . 请注意,不要使用alert() Get used to using the DevTools console, console.log() , console.dir() (for objects) and the debugger. 习惯使用DevTools控制台, console.log()console.dir() (对象)和调试器。 It will serve you much better when your code gets more complex, uses pretty standard debugging methods common in other environments, and it's really not that hard to learn. 当代码变得更复杂时,它将为您提供更好的服务,使用在其他环境中常见的非常标准的调试方法,而且实际上并不难理解。 Start here https://developers.google.com/web/tools/chrome-devtools/javascript/ 从这里开始https://developers.google.com/web/tools/chrome-devtools/javascript/

Just compare the input value with the value 9000 when the button is click. 只需在单击按钮时将输入值与值9000进行比较。 All you need is 5 lines (or less if you skip creating a variable for input) like this: 您只需要5行(如果您跳过创建输入变量,则为更少行),如下所示:

 /* JavaScript */ var input = document.getElementById("takeinput"); function checkSoul() { alert( (input.value < 9000) ? "not enough souls" : "Too much souls" ); } document.getElementById("button").addEventListener("click", checkSoul); 
 <!-- HTML --> <div> <h1> How many Souls have you aquired? </h1> <form id="number_of_souls"> <input id="takeinput"> Souls <button id="button">submit</button> </form> </div> 


You can shorten this further to just two lines (or less if you skip creating a variable for input) using ES6 like this: 您可以使用ES6将此进一步缩短为两行(如果您跳过创建输入变量,则更少),如下所示:

 /* JavaScript */ var input = document.getElementById("takeinput"); document.getElementById("button").addEventListener("click", () => { alert( (input.value < 9000) ? "not enough souls" : "Too much souls" ) }); 
 <!-- HTML --> <div> <h1> How many Souls have you aquired? </h1> <form id="number_of_souls"> <input id="takeinput"> Souls <button id="button">submit</button> </form> </div> 

NB If you are planning to use ES6, you'll need Babel to compile your ES6 to ES5 before pushing your JavaScript to production though since browsers don't support ES6 yet). 注意如果您打算使用ES6,那么在推动您的JavaScript投入生产之前,您需要Babel将ES6编译为ES5,因为浏览器还不支持ES6)。

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

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