简体   繁体   English

JavaScript,如果输入类型范围条件

[英]Javascript, if input type range condition

I am trying to figure out what's wrong with my script. 我试图找出我的脚本出了什么问题。 When the input reaches 1, it should display the alert but it does't. 当输入达到1时,它应该显示警报,但不显示。 But if i replace (value === 1) with (value === value), it displays the alert every time i change the input. 但是如果我用(value === value)替换(value === 1),则每次我更改输入时都会显示警报。 So i know the problem is with the syntax "(value === 1)". 所以我知道问题出在语法“(value === 1)”。 I tried everything. 我尝试了一切。 5 hours weren't enough for me to find a solution on the internet, so i hope someone tells me if i made mistake with the syntax or something. 5个小时不足以让我在互联网上找到解决方案,所以我希望有人告诉我语法或其他方面是否有误。 Thank you for your time. 感谢您的时间。

 <input id="carrotate123" type="range" min="0" max="3" value="2" oninput="getInput(this.value)"> <script> function getInput(value) { var rangeInput = document.getElementById("carrotate123").value; var value = rangeInput.value; if (value === 1) { alert("First"); } } </script> 

The === operator means strict equality - both in value and in type. ===运算符表示严格相等-值和类型均如此。 In your case, value is a string ( value property of DOM elements usually returns a string ) while 1 is obviously a number . 在您的情况下, value是一个string (DOM元素的value属性通常返回一个string ),而1显然是一个number Consider the examples below: 请考虑以下示例:

1 == 1 // true
1 == "1" // true
1 === 1 // true
1 === "1" // false

You should consider changing === to == (which performs automatic type coercion) or compare your value with "1" (as a string). 您应该考虑将===更改为== (执行自动类型强制),或者将您的值与"1" (作为字符串)进行比较。

More about differences between comparison operators: Expressions and operators 有关比较运算符之间差异的更多信息: 表达式和运算符

You have two things wrong here. 您在这里有两件事错了。 First, you have an extra call to value . 首先,您需要额外致电value The cleanest solution to that is to remove the one on the rangeInput assignment. 最干净的解决方案是删除rangeInput分配中的一个。 But you could also simply use that value and skip defining rangeInput altogether. 但是,您也可以简单地使用该值,而完全跳过定义rangeInput

The second one is covered in the answer from Szab. Szab的回答涵盖了第二个问题。 You need to change how you compare your target value with the String supplied by the input element. 您需要更改将目标值与input元素提供的字符串进行比较的方式。 Combining these looks like this: 结合这些看起来像这样:

 <input id="carrotate123" type="range" min="0" max="3" value="2" oninput="getInput(this.value)"> <script> function getInput(value) { var rangeInput = document.getElementById("carrotate123"); var value = rangeInput.value; // or replace the previous two lines with // var value = document.getElementById("carrotate123").value if (value == 1) { // or: if (value === '1') alert("First"); } } </script> 

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

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