javascript - 如何根据特定条件禁用和启用 javascript 按钮?
问题描述
我想在加载此页面并且这些按钮之间的值等于 1 时禁用 (-) 按钮。
1)hbs代码
<tbody>
{{#each products}}
<tr>
<h1 id="Quantity" hidden>{{this.quantity}}</h1>
<td><img src="/product-images/{{this.product._id}}.jpg" style="width:70px;height:70px" alt="">
</td>
<td>{{this.product.Name}}</td>
<td>Rs.{{this.product.Price}}</td>
<td>
<button class="btn btn-info mr-3 cart-item-count" id="button(-)"
onclick="changeQuantity('{{this._id}}','{{this.product._id}}','{{../user._id}}',-1)">-</button>
<span id="{{this.product._id}}">{{this.quantity}}</span>
<button class="btn btn-info mr-3 cart-item-count" id="button(-)"
onclick="changeQuantity('{{this._id}}','{{this.product._id}}','{{../user._id}}',1)">+</button>
<td>
<button type="button" class="btn btn-danger">Remove</button>
</td>
</tr>
{{/each}}
</tbody>
2)产品阵列
3) 用于按钮禁用和启用的代码。
let Quantity = document.getElementById('Quantity').innerHTML
console.log(Quantity)
if (Quantity == 1) {
document.getElementById('button(-)').disabled = true
} else {
document.getElementById('button(-)').disabled = false
}
function changeQuantity(cartId, proId, userId, count) {
count = parseInt(count)
let quantity = parseInt(document.getElementById(proId).innerHTML)
let qty = quantity + count
console.log(qty)
if (qty > 1 ) {
document.getElementById('button(-)').disabled = false
} else if (qty == 1 || qty==10) {
document.getElementById('button(-)').disabled = true
}
if(qty==10){
document.getElementById('button(+)').disabled = true
}else{
document.getElementById('button(+)').disabled = false
}
$.ajax({
url: '/change-product-quantity',
data: {
cart: cartId,
product: proId,
user: userId,
count: count,
quantity: qty
},
method: 'post',
success: (response) => {
document.getElementById(proId).innerHTML = quantity + count
document.getElementById('total').innerHTML = response.total
}
})
}
笔记:
当购物车页面只有一组产品时,上面的代码工作正常。但是,如果有多个产品列表(如上图所示),它不会像我预期的那样工作。换句话说,我想分别控制每个产品的按钮,而不会相互覆盖。
怎么做 ?
解决方案
使用唯一 ID 识别每个产品将有助于解决此问题。
推荐阅读
- c++ - C++ 已用时间 = 0
- angular - Angular Universal无法读取未定义的属性“某些”
- email - 是否可以在移动设备上禁用 AMP 电子邮件?
- python - 是否可以使用 python 运行 gmt 脚本(csh 文件)?
- bash - 如何在whiptail中循环case语句
- sql - 将 sysdate 转换为 BST(英国夏令时)
- python - 如何将多行文本小部件写入文本文件的单行?
- javascript - 重构帮助减少 JavaScript 中的一些数组数据对象
- android - Android 10:如何在没有 /proc/net/arp 的情况下从 Socket / Client PC 获取 MAC 地址
- python - python中的反向DNS查找返回错误的主机