JQuery 访问输入字段值

JQuery Accessing Input feild value

我正在尝试使用 JQuery 中的代码,我为两个按钮添加了两个事件。 1 表示增加 1,1 表示减少 1。然而,减少 1 是正常的,但增加 1 而不是将值增加 1,它是在值中附加 1,即 1、11、111、1111。 我该如何解决这个问题。 我是不是做错了什么。

$(document).ready(function () {

$("button.decreament").click(function () {
    let x = $(this).siblings("input").val()
    if (x >= 1) {
        $(this).siblings("input").val(x - 1);
    }
});

$("button.increament").click(function () {
    let x = $(this).siblings("input").val()
        $(this).siblings("input").val(x + 1);
}); 

});

发生这种情况是因为 + 超载了。它就像字符串的连接运算符。要消除这种混淆,您可以像这样使用它。

$(this).siblings("input").val(parseInt(x) + 1); 
or,
$(this).siblings("input").val(parseInt(x) + parseInt(1));

原因是您将变量连接为字符串而不是添加数字。在变量前添加一个 + ,代码会将变量视为数字。

这应该适合你 => $(this).siblings("input").val(+x + 1);

下面是一个示例片段:

$(document).ready(function() {
  var sval = $(".value");
  var reduce = $(".reduce");
  reduce.click(function() {
    let $this = $(this).val();
    let value = sval.text();    
    $this = (+$this - 1); //<-- +$this is now treated as a number
    value = (+value - 1); //<-- +value is now treated as a number
    reduce.val($this);
    sval.text(value);
    console.log('single item reduced by 1: ' + value);
    console.log('increment increased by 1: ' + $this);
  });
  var add = $(".add");
  add.click(function() {
    let $this = $(this).val(); 
    let value = sval.text(); 
    $this = (+$this + 1); //<-- +$this is now treated as a number
    value = (+value + 1); //<-- +$value is now treated as a number  
    add.val($this);
    sval.text(value);
    console.log('single item increased by 1: ' + value); 
    console.log('increment increased by 1: ' + $this);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Decrement: <input type="button" class="reduce" value="4"> Increment: <input type="button" class="add" value="4"> Single value: <span class="value">10</span>