英文:
When I go between if I go between 3 and 10, its marked as greater than 20
问题
如果元素Wager设置为大于3且小于10,JavaScript会将其标记为大于20。我原本预期在3和10之间的任何值都会被标记为小于20,但似乎有一些愚蠢的问题。
英文:
If the the element Wager is set to anything above 3 and under 10. Javascript marks it as above 20.
<input type="number" id="wager" step="0.1" min="0.1" max="20.0" placeholder="0.1"/>
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(1);
console.log(this.value) // Shows the current value (debugging)
console.log(this.max) // Shows the max value allowed (debugging)
console.log(this.value > this.max) // Shows if its above the max allowed (debugging)
if (this.value > this.max) {
this.value = this.max
}
if (this.value < 0.1) {
this.value = 0.1
}
}
I was expecting so anything between 3 and 10 would be marked as lower than 20 but yeh. It probably is something stupid.
答案1
得分: 0
这种行为是由比较字符串引起的。首先,this.value
和 this.max
从HTML元素中返回字符串,即使在分配了数值后仍然是字符串。其次,toFixed()
方法也返回一个字符串。因此,我们将在比较值之后应用它。
function setTwoNumberDecimal(event) {
var _thisValue = parseFloat(this.value);
var _thisMin = parseFloat(this.min);
var _thisMax = parseFloat(this.max);
if (_thisValue > _thisMax) {
this.value = _thisMax.toFixed(1);
} else if (_thisValue < _thisMin) {
this.value = _thisMin.toFixed(1);
} else {
this.value = _thisValue.toFixed(1);
}
}
英文:
This behavior is a result of comparing strings. First, this.value
and this.max
return strings from the HTML element, even after being assigned a number value. Second, the method toFixed()
also returns a string. Instead we'll apply it after comparing values.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function setTwoNumberDecimal(event) {
var _thisValue = parseFloat(this.value);
var _thisMin = parseFloat(this.min);
var _thisMax = parseFloat(this.max);
if (_thisValue > _thisMax) {
this.value = _thisMax.toFixed(1);
} else if (_thisValue < _thisMin) {
this.value = _thisMin.toFixed(1);
} else {
this.value = _thisValue.toFixed(1);
}
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论