javascript - 增加和减少检查不工作的10、100、1000等等
问题描述
我尝试检查我的输入是增加还是减少,除了数字 10、100、1000 等之外,这工作正常。我已经尝试了几个代码,但它们都不起作用。这里有些例子:
$(document).ready(function(){
var professional = $("#professional");
var oldValue = professional.val();
professional.data("oldValue", oldValue);
$("#professional").change(function(){
var oldValue = $(this).data("oldValue");
var newValue = $(this).val();
if (newValue > oldValue)
alert("increase!");
else
alert("decrease!");
$(this).data("oldValue", newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="quantity">
<label for="professional">Professional</label><br>
<input type="number" class="price" id="professional" min="0" value="9">
</div>
$(document).ready(function() {
$("#professional").attr('data-prev-val', $("#professional").val());
$("#professional").change(function() {
var newValue = $(this).val();
if (newValue > $(this).attr('data-prev-val'))
alert("increase!");
else
alert("decrease!");
$("#professional").attr('data-prev-val', newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="quantity">
<label for="professional">Professional</label><br>
<input type="number" class="price" id="professional" min="0" value="9">
</div>
还有其他方法,但它们都有相同的问题。有谁知道这是为什么以及如何解决?
解决方案
您应该使用parseInt
,因为当前值认为是字符串。
$(document).ready(function() {
$("#professional").attr('data-prev-val', $("#professional").val());
$("#professional").change(function() {
var newValue = parseInt($(this).val());
if (newValue > parseInt($(this).attr('data-prev-val')))
alert("increase!");
else
alert("decrease!");
$("#professional").attr('data-prev-val', newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="quantity">
<label for="professional">Professional</label><br>
<input type="number" class="price" id="professional" min="0" value="9">
</div>
推荐阅读
- python - 如何将2个字符串转换为列表python?
- ruby - 我需要关于 string.index 的建议
- c++ - gcc 编译的 C++ 中不包含调试符号
- symfony - Twig 检索模板 symfony 中翻译的所有变量
- python - 有效地检查数据框的日期是否在一个范围内,并返回一个计数
- powerbi - 在 Power BI 中合并来自多个工作簿的 Excel 工作表
- json - 如何序列化 Template::render 的上下文
- guice - 是否可以使用 Guice 注入任意类型的实现?
- jquery - JSON 对象值与 HTML 表单值不同
- jquery - Onclick用jQuery替换div中的项目信息