如何获取点击按钮的数据属性值?

2 javascript jquery dataset

我想获取单击按钮的数据属性值。当我提交ajax表单时我需要使用它。我怎样才能得到那个?

我的按钮(有多少个产品就有多少个按钮)

<input value="Add To Cart" type="button" class="btn btn-success btn-sm btn-block add-to-card-button" data-id="{{$product->id}}" style="margin-bottom:10px">
Run Code Online (Sandbox Code Playgroud)

JavaScript 代码;

const cartButton = document.getElementsByClassName('add-to-card-button');

if (cartButton) {
    Array.from(cartButton).forEach(function(element) {
        element.addEventListener('click', addToCard);
    });
   }

function addToCard() {

    $.ajax({
        url: "/auth/check",
        context: document.body,
        success: function(status){
           if (status === "Auth")
           {
               addToCardForUsers();
           } else {
               addToCardForGuests()
           }
        }
    });

}

function addToCardForUsers() {

    $.ajax({
        type: 'POST',
        url: "/cart/add-product/"+ cartButton.dataset.id,
        context: document.body,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(){
                if(countProduct.text() == null) {
                    countProduct.text(1);
                } else {
                    countProducts =  Number(countProduct.text());
                    countProducts++;
                    countProduct.text(countProducts);
                }              
                Flash.success("Product succesfully added to your cart");
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

ima*_*u15 5

更改将事件监听器绑定到此的方式,

$('.add-to-card-button').on('click', function () {
    addToCard();
    alert($(this).data('id'));
});
Run Code Online (Sandbox Code Playgroud)