首页 文章

如何为每个项目的订单按钮设置最大点击次数? (JavaScript的)

提问于
浏览
0

在警报显示他试图订购的产品缺货之前,我需要5次(例如)

他当然可以订购其他未被点击过5次的产品 .

我面临的问题是我不知道如何保持每个订单按钮的数量(锚点充当按钮) .

我尝试实现该功能,它确实显示警报,但它需要点击所有订单按钮 .

这就是我的函数的样子:

let counter = 0; //global variable
function order_func() {
    let every_product= document.querySelectorAll(".all_prods");
    for (let each_prod = 0; each_prod < every_product.length; each_prod++) {
        every_product[each_prod].addEventListener("click", function (e) {
        if(count_stuff < 10){
                add_it(e, each_prod); //e to preventDefault() and console.log "each_prod"
            count_stuff++;
        }else{
            out_of_stock(e); //shows the alert it takes the event as argument to prevent default behavior.
        }

        });
    }

}

add_it() 只是 console.log() 的产品 .

我只使用vanilla JS,我不想使用任何其他库:)谢谢!

1 回答

  • 0

    您可以使用data属性在页面中存储临时值 . 使用JQuery看一下这个例子 .

    <!-- index.html -->
    <a href="" id="order-btn" data-count="0" data-max-counts="5">Order</a>
    
    <script>
    $('#order-btn').click(function() {
        var maxCounts = this.data('maxCounts');
        var count = this.data('count');
        if (count >= maxCount) {
           alert('you cant order any more');
           return;
        }
        this.data('count',count++);
    
       // other logic .e.g Ajax call
    
    })
    </script>
    

    你可以使用vanilla JS来做到这一点:

    <script>
        let counter = 0; //global variable
            function order_func() {
               let every_product= document.querySelectorAll(".all_prods");
               for (let each_prod = 0; each_prod < every_product.length; each_prod++) {
                 every_product[each_prod].addEventListener("click", function (e) {
                   var count_stuff = e.target.dataset.count; // or this.dataset.count
                   var max_count = e.target.dataset.maxCounts; // or this.dataset.maxCounts
                   if(count_stuff < max_count){
                      add_it(e, each_prod); 
                      e.target.dataset.count = count_stuff++;
                   }else{
                     out_of_stock(e); 
                   }
    
            });
        }
    
    }
    </script>
    

相关问题