首页 > 解决方案 > 如何从单击的特定按钮中添加和删除 id?

问题描述

    <script>
 $(document).ready(function() {

        $("button").on('click', function(argument) {  
         $("button").attr('id', 'addtocart');
            var product_id = $("#product_id").val();
                if (product_id!="") {
                        $.ajax({
                            type : "POST",
                            url : "manage-cart.php",
                            data : 'product_id='+product_id,
                            success : function (response) {
                                // action to be performed if                                             successful
                                $('#addtocart').removeAttr('id');
                            }
                    })

                    }
                    
                })
            });
        </script>

   
    <div class="buttons">
     <button class="" type="submit" >
       <i class="fa fa-shopping-cart"></i>Add to Cart</button>
 </div>
  <input type="hidden" id="product_id" value ="5">
<div class="buttons">
     <button class="" type="submit" >
       <i class="fa fa-shopping-cart"></i>Add to Cart</button>
 </div>
  <input type="hidden" id="product_id" value ="6">
<div class="buttons">
     <button class="" type="submit" >
       <i class="fa fa-shopping-cart"></i>Add to Cart</button>
 </div>
  <input type="hidden" id="product_id" value ="7">
<div class="buttons">
     <button type="submit" >
       <i class="fa fa-shopping-cart"></i>Add to Cart</button>
 </div>
  <input type="hidden" id="product_id" value ="8">

这是我正在使用的脚本和 HTML 代码。单击按钮时,会将 ID 添加到所有按钮中,这不是我希望将 ID 添加到仅单击的按钮并在执行 ajax 脚本后删除的想法。

标签: javascriptjquery

解决方案


你需要使用$(this)

 $(document).ready(function() {

    $("button").on('click', function(argument) {  
      var _t = $(this);
     _t.attr('id', 'addtocart');
        var product_id = $("#product_id").val();
            if (product_id!="") {
                    $.ajax({
                        type : "POST",
                        url : "manage-cart.php",
                        data : 'product_id='+product_id,
                        success : function (response) {
                            // action to be performed if                                             successful
                            _t.removeAttr('id');
                        }
                })

                }

            })
        });
    </script>

推荐阅读