我正在尝试遵循JQuery中的代码,我为两个按钮添加了两个事件。 1代表增加1,1代表减少1。但是,减少1可以正常工作,但是增加1而不是增加1会在值1、11、111、1111后面附加1。我该如何解决这个问题。我做错什么了。
$(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));
原因是您将变量串联为字符串,而不添加数字。在变量前面添加+
,代码会将变量视为数字。
$(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>