最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - PayPal express checkout integration with multiple buttons on one page - Stack Overflow

programmeradmin0浏览0评论

I currently have a list of items with a Paypal button associated with each of them. Each item will be purchased separately by clicking on its associated button.

<ul>
    <li data-id="1">Item 1 <div class="paypal-button"></div></li>
    <li data-id="2">Item 2 <div class="paypal-button"></div></li>
    <li data-id="3">Item 3 <div class="paypal-button"></div></li>
</ul>

<script src=".js"></script>

<script>
    paypal.Button.render({
        // options
    }, '.paypal-button');
</script>

Unfortunately, it seems that paypal.Button.render() will only render the first element that it finds.

Is it possible to do this call on multiple elements?

I currently have a list of items with a Paypal button associated with each of them. Each item will be purchased separately by clicking on its associated button.

<ul>
    <li data-id="1">Item 1 <div class="paypal-button"></div></li>
    <li data-id="2">Item 2 <div class="paypal-button"></div></li>
    <li data-id="3">Item 3 <div class="paypal-button"></div></li>
</ul>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<script>
    paypal.Button.render({
        // options
    }, '.paypal-button');
</script>

Unfortunately, it seems that paypal.Button.render() will only render the first element that it finds.

Is it possible to do this call on multiple elements?

Share Improve this question asked Mar 22, 2017 at 15:45 MikeyMikey 6,7664 gold badges24 silver badges49 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

You need to give each element a unique id, then call render multiple times:

<ul>
    <li data-id="1">Item 1 <div id="button-1"></div></li>
    <li data-id="2">Item 2 <div id="button-2"></div></li>
    <li data-id="3">Item 3 <div id="button-3"></div></li>
</ul>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<script>
    [ '#button-1', '#button-2', '#button-3' ].forEach(function(selector) {
        paypal.Button.render({
            // options
        }, selector);
    });
</script>

If you don't like keeping track of IDs like me, you can use classes instead. And use data attributes to differentiate.

<div class="paypal-button" data-my-attribute="tree"></div>
<div class="paypal-button" data-my-attribute="dog"></div>
<div class="paypal-button" data-my-attribute="car"></div>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<script>
    document.querySelectorAll('.paypal-button').forEach(function(selector) {
        paypal.Button.render({
            // options
            console.log( selector.dataset.myAttribute );
        }, selector);
    });
</script>
发布评论

评论列表(0)

  1. 暂无评论