jquery - 增加,减少输入中的值并且不显示负数
问题描述
我正在尝试制作输入表单,它的值可以通过单击 +1 / -1 按钮来增加和减少,我也有 +5 / -5 按钮。
当值为 3 并单击 -5 按钮时,值变为 -2。但我不想显示负数。我希望最小数字始终为“0”。甚至结果值也是负数。
如何修复代码?
$(function() {
$(".plus").click(function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.siblings('input');
var value = parseInt($input.val());
if (value < 30) {
value = value + 1;
} else {
value = 30;
}
$input.val(value);
});
$(".plus2").click(function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.siblings('input');
var value = parseInt($input.val());
if (value < 30) {
value = value + 5;
} else {
value = 30;
}
$input.val(value);
});
$(".minus").click(function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.siblings('input');
var value = parseInt($input.val());
if (value > 0) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
});
$(".minus2").click(function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.siblings('input');
var value = parseInt($input.val());
if (value > 0) {
value = value - 5;
} else {
value = 0;
}
$input.val(value);
});
});
.change_qty {
display: inline-block;
color: #fff;
background: #2e748e;
width: 22px;
height: 22px;
border-radius: 50%;
font-weight: 900;
line-height: 22px;
}
.cursor_hover {
cursor: hand;
cursor: pointer;
}
.change_qty {
display: inline-block;
color: #fff;
background: #2e748e;
width: 22px;
height: 22px;
border-radius: 50%;
font-weight: 900;
line-height: 22px;
}
.cursor_hover {
cursor: hand;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="margin-bottom:2em;text-align:center;">
<div class="change_qty minus2 cursor_hover">-5</div>
<div class="change_qty minus cursor_hover">-1</div>
<input type="numeric" style="height:22px;width:40px;margin:0 .5em;text-align:center;" value="0">
<div class="change_qty plus cursor_hover">+1</div>
<div class="change_qty plus2 cursor_hover">+5</div>
</div>
这就是我在这里尝试的 http://jsfiddle.net/a5ktensk/63/
解决方案
只需更改 if 语句就可以了。
http://jsfiddle.net/a5ktensk/68/
if (value > 5) {
value = value - 5;
}
else {
value = 0;
}
另一种选择是。
value = value -5;
if(value < 0) {
value = 0;
}
推荐阅读
- react-native - 我的项目中未显示的图像反应原生
- sql-server-2014 - 我该如何解决“您不能更改 'dbo.tb_dept_change' ,因为它是不兼容的对象类型”?
- django - 如何在业务逻辑视图中将 AbstractUser 链接到组和查询
- r - 如何将此光线着色器图转换为 Gif?
- angular - 如何在 webview 上调用 angular8 组件的功能?
- c# - 如何制作开机定时器?
- excel - 使用 VBA 将图片插入并链接到形状填充中
- docker - 如何升级 kubectl 服务器版本
- kubernetes - terraform azurerm - 无法破坏公共 IP
- python - 如何使我的代码可停止?(不杀/打断)