简体   繁体   English

使用minicart.js显示购物车中的项目数

[英]Show number of items in cart with minicart.js

Question: How can I show the number of items in a user's cart using the minicart.js script? 问题:如何使用minicart.js脚本显示用户购物车中的物品数量?

Backstory: I'm developing a static HTML website that is selling a small number of products using standard PayPal buttons and minicart.js 背景:我正在开发一个静态HTML网站,该网站使用标准的PayPal按钮和minicart.js销售少量产品

I'd like to have an area in the header of my website that displays the number of items currently in the "cart", but I can't figure out how to do so. 我想在我的网站标题中保留一个区域,以显示“购物车”中当前的商品数量,但是我不知道该怎么做。 There is no example detailing this functionality on the minicart.js website. 在minicart.js网站上没有详细说明此功能的示例。

I'm sure it can be done, but I'm at a loss. 我敢肯定这是可以做到的,但我很茫然。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

You can get like this: 您可以这样获得:

paypal.minicart.cart.items().length

It works for me 这个对我有用

I managed to figure out a way to achieve what I'm looking for by finding the necessary variable set through minicart.js and then manipulating it via jQuery. 我设法找到了一种方法,方法是通过minicart.js找到必要的变量集,然后通过jQuery进行操作。

minicart.js gives me the following variable which outputs the current cart total: minicart.js给了我以下变量,该变量输出当前购物车的总额:

paypal.minicart.cart.total();

I then took that variable and applied some jQuery that converted this variable into a separate variable called "cartTotal" which is checked and updated every time a user interaction happens on the page (ie - a click or a keypress). 然后,我使用该变量,并应用了一些jQuery,将其转换为一个单独的变量,称为“ cartTotal”,每次在页面上发生用户交互(即单击或按键)时都会对其进行检查和更新。 I found that a brief delay was needed in order for everything to work properly. 我发现需要短暂的延迟才能使所有功能正常运行。 Interestingly, the keypress check needs a longer delay than the mouse click. 有趣的是,按键检查比鼠标单击需要更长的延迟。

My final (for now) working code is as follows: 我最终的(现在)工作代码如下:

$( document ).ready(function() {
     var cartTotal = paypal.minicart.cart.total();
        $('input#cart').val('$' + cartTotal);

    $( "body" ).click(function() {
            setTimeout(function() { // Setting slight delay on function to accomodate for button push of removing items from cart
             var cartTotal = paypal.minicart.cart.total();
            $('input#cart').val('$' + cartTotal);
        }, 100);
    });


    $( "body" ).keypress(function() {
       setTimeout(function() { // Setting longer delay on function to accomodate for key push of removing items from cart
             var cartTotal = paypal.minicart.cart.total();
            $('input#cart').val('$' + cartTotal);
        }, 900);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM