首页 > 解决方案 > 如何根据特定条件禁用和启用 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

            }
        })
    }

笔记:

当购物车页面只有一组产品时,上面的代码工作正常。但是,如果有多个产品列表(如上图所示),它不会像我预期的那样工作。换句话说,我想分别控制每个产品的按钮,而不会相互覆盖。

怎么做 ?

标签: javascriptajaxmongodbfunctionexpress-handlebars

解决方案


使用唯一 ID 识别每个产品将有助于解决此问题。


推荐阅读