gpt4 book ai didi

javascript - 递增和递减按钮

转载 作者:行者123 更新时间:2023-11-28 13:03:03 25 4
gpt4 key购买 nike

我是 jQuery 新手,但正在尝试学习一些非常基本的东西。我只是想建立自动递增/递减输入字段,如下所示:

<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button class="bottone piu">+</button>
<button class="bottone meno">-</button>
</div>
<script>
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>

为什么如果我将 div 放入表单中它不起作用?

编辑非常感谢

最佳答案

按钮默认为提交类型。因此,当您将其放入表单中并单击按钮时,您的表单就会被提交。更改类型将解决您的问题,如下所示

<!DOCTYPE html>
<html>

<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>
<script>
$(document).ready(function() {
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>

</html>

关于javascript - 递增和递减按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com