【问题标题】:How to read the data-product_id from the following code如何从以下代码中读取 data-product_id
【发布时间】:2019-04-30 14:04:23
【问题描述】:

我有一个脚本,它在 woocommerce 中捕捉到我将产品添加到我的购物车的事件。

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

按下ADD_TO_CART按钮后

console.log(this_button);

我得到了这个答案,并在其中看到了我想要的 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, … }

现在的问题是如何从这个序列中找到 data-product_id 的值。 这个问题实际上与 woocomerce 无关,而是与 JS 本身有关。 提前感谢您的所有帮助。

【问题讨论】:

  • 对不起,我已经完成了,
  • 如果您找到了解决方案,请发布答案,以便我们大家学习。

标签: javascript ajax wordpress woocommerce


【解决方案1】:

您可以通过将其添加到您的 .click() 函数来检索该值。

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

试一试:

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

【讨论】:

  • 对不起,我对JS的了解实在是太少了,不知道怎么办。
【解决方案2】:

我唯一可以建议你的是尝试调用:

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

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

记得负责任地喝这个烧瓶。 :)

【讨论】:

  • 不幸的是,他回来了:undefined &lt;script&gt; (function($){ $('body').on( 'added_to_cart', function(e, fragments, cart_hash, this_button){ console.log(this_button.context['data-product_id']) }); })(jQuery); &lt;/script&gt;
猜你喜欢
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多