基于Javascript實(shí)現(xiàn)頁面商品個數(shù)增減功能
更新時間:2023年08月09日 17:12:48 作者:梁云亮
本文給大家介紹基于Javascript實(shí)現(xiàn)頁面商品個數(shù)增減功能,通過點(diǎn)擊數(shù)量增減個數(shù),代碼分為前端頁面,后臺返回代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
效果

后臺返回代碼
Map<GoodsVO, Integer> cart = new HashMap();
cart.put(new GoodsVO(1001,"蘋果",100),5);
cart.put(new GoodsVO(1002,"桔子",300),3);
cart.put(new GoodsVO(1003,"香蕉",150),3);
request.getSession().setAttribute("cat",cart);前端頁面
<c:forEach items="${cart}" var="item">
<tr>
<td>${item.key.name}</td>
<td>
<span id="subSpan${item.key.id}" class="subSpan">-</span>
<input type="text" id="amountInput${item.key.id}" value="${item.value}" style="width: 40px;">
<span id="addSpan${item.key.id}" class="addSpan">+</span>
<input type="hidden" id="stockInput" value="${item.key.stock}">
</td>
</tr>
</c:forEach>
<script src="assets/js/jquery3.6.0.js"></script>
<script>
//購買商品數(shù)量減1
$(".subSpan").click(function () {
let subSpanId = $(this).attr("id");
let id = subSpanId.substring(7);
let amount = $("#amountInput" + id).val();
if (amount - 1 <= 0) {
alert("所購商品數(shù)量不能小于等于0");
return;
}
$("#amountInput" + id).val(amount - 1);
})
//購買商品數(shù)量加1
$(".addSpan").click(function () {
let addSpanId = $(this).attr("id");
let id = addSpanId.substring(7);
let amount = $("#amountInput" + id).val();
let stock = $("#stockInput").val();
if (amount > stock) {
alert("所購商品數(shù)量不能大于庫存");
return;
}
$("#amountInput" + id).val(amount + 1);
})
</script>實(shí)現(xiàn)二(重點(diǎn))
<div class="jia_jian">
<img class="jian" style="height: 25px;width: 21px;" src="images/jian.jpg"/>
<input class="shuliang" type="text" value="1"/>
<img class="jia" style="height: 25px;width: 21px;" src="images/jia.jpg"/>
<input type="hidden" value="5">
</div>
<script type="text/javascript">
//購買商品數(shù)量減1
$(".jian").click(function () {
let amount = $(this).next().val();
if (amount - 1 <= 0) {
alert("所購商品數(shù)量不能小于等于0");
return;
}
$(this).next().val(amount - 1);
})
//購買商品數(shù)量加1
$(".jia").click(function () {
let amount = $(this).prev().val();
let stock = $(this).next().val();
if (amount >= stock || amount>=200) {
alert("所購商品數(shù)量不能大于庫存 或 最多只能買200個");
return;
}
$(this).prev().val(1+Number(amount));
})
</script>到此這篇關(guān)于Javascript實(shí)現(xiàn)頁面商品個數(shù)增減功能的文章就介紹到這了,更多相關(guān)js商品個數(shù)增減內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
typescript類型體操及關(guān)鍵字使用示例詳解
這篇文章主要為大家介紹了typescript類型體操及關(guān)鍵字使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
聯(lián)合類型Union?Types與交叉類型Intersection?Types區(qū)別解析
這篇文章主要為大家介紹了聯(lián)合類型Union?Types與交叉類型Intersection?Types區(qū)別詳解2023-06-06
rollup?cli開發(fā)全面系統(tǒng)性rollup源碼分析
這篇文章主要為大家介紹了rollup?cli開發(fā)全網(wǎng)系統(tǒng)性rollup源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
數(shù)據(jù)結(jié)構(gòu)TypeScript之鏈表實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了數(shù)據(jù)結(jié)構(gòu)TypeScript之鏈表實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01

