首页 > 解决方案 > 增加和减少检查不工作的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>

还有其他方法,但它们都有相同的问题。有谁知道这是为什么以及如何解决?

标签: javascriptjquery

解决方案


您应该使用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>


推荐阅读