How to read the data-product_id from the following code

六眼飞鱼酱① 提交于 2021-01-29 05:07:09

问题


I have a script that in woocommerce catches me an event of adding a product to my cart.

    <script>
        (function($){
           $('body').on( 'added_to_cart', function(e, fragments, cart_hash, this_button){
              console.log('this_button:',this_button);
           });
        })(jQuery);
    </script>

After pressing the ADD_TO_CART button in the

console.log(this_button);

I get this answer and in it I see my desired product_id

this_button: 
{…}
​
0: <a class="button product_type_simple add_to_cart_button ajax_add_to_cart added" href="/Blog/produkt/klawwa/?add-to-cart=14" data-quantity="1" data-product_id="14" data-product_sku="" aria-label="Dodaj “Fajna flaszka” do koszyka" rel="nofollow">
​
context: <a class="button product_type_simple add_to_cart_button ajax_add_to_cart added" href="/Blog/produkt/klawwa/?add-to-cart=14" data-quantity="1" data-product_id="14" data-product_sku="" aria-label="Dodaj “Fajna flaszka” do koszyka" rel="nofollow">
​
length: 1
​
selector: ""
​
__proto__: Object { jquery: "1.12.4", constructor: n(), length: 0, … }

And now the question how to find the value of data-product_id from this sequence. The question is not actually related to woocomerce but to JS itself. Thank you in advance for all your help.


回答1:


You can retrieve the value by adding this to your .click() function.

$(this).data('product_id');

TRY:

 <script>
        (function($){
           $('body').on( 'added_to_cart', function(e, fragments, cart_hash, this_button){
              console.log($(this_button).data('product_id'));
           });
        })(jQuery);
    </script>



回答2:


The only thing I can suggest you is to try call:

console.log(this_button.context['data-product_id'])
//returns undefined 

or

console.log(this_button[0]['data-product_id'])

And remember to drink this flaszka responsibly. :)



来源:https://stackoverflow.com/questions/55922697/how-to-read-the-data-product-id-from-the-following-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!