我在输入字段的两边都有简单的加号和减号按钮,如下面的代码所示
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />
目的是在添加房间时添加或减去房间,jquery 函数为
function add() {
var a = $("#noOfRoom").val();
a++;
if (a => 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
但出现如下问题
- 当我在初始阶段单击减号 (-) 按钮时,输入框中会显示 -1,默认情况下应禁用减号 (-) 按钮以使房间号为负数。
- 每次点击加号或减号按钮时,数字都会加 2 或减 2。我该如何解决?
最佳答案
更新添加 fiddle https://fiddle.jshell.net/n7ug52dr/
每次点击只会加减1,不会显示-1
您可以像这样编辑代码:
function add() {
var a = $("#noOfRoom").val();
a++;
if (a && a >= 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
// this is wrong part
if (b && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
关于javascript - jQuery 递增或递减变量 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35219776/