如何从复选框事件函数中获取商品数组并传递给PayPal多商品明细参数
问题原因
你当前的代码存在三个核心问题导致无法正确传递商品明细:
paypalItem是在checkbox的change事件回调内部声明的局部变量,外部作用域(包括PayPal的createOrder方法)无法访问到该变量- 你重复绑定了两次
input[type="checkbox"]的change事件,逻辑冗余,且第二次事件中给this.paypalItem赋值的操作指向的是当前遍历的checkbox元素,无实际作用 createOrder方法中items: item的item变量未定义,且description字段写死为字符串,没有取实际的用户输入值
另外你的HTML中label的for属性值和对应input的id不匹配,会导致点击label无法选中对应的checkbox,也会导致你之前取商品名称的逻辑失效。
修改方案
1. 代码修改步骤
- 在全局作用域声明
paypalItem数组,所有回调都可以访问修改该变量 - 合并两次checkbox change事件逻辑,同时更新总金额和商品明细数组
- 修正商品名称的获取逻辑,适配HTML结构
- 修改
createOrder方法,直接取全局paypalItem作为items参数,修正description的动态取值
2. 完整修正后代码
JS代码
// 全局声明商品明细数组,所有作用域均可访问 let paypalItem = []; //Pull HTML elements and store as JS variables let pp_div = document.querySelector("#paypal-button-container"); let input_form = document.querySelector("#input_form"); let input = document.querySelector("#input"); let total = document.querySelector("#Total"); // 合并checkbox change事件逻辑,无需重复绑定 $('input[type="checkbox"]').change(function(){ let totalprice = 0; paypalItem = []; // 每次变更先清空原有明细 $('input[type="checkbox"]:checked').each(function(){ let curPrice = parseInt($(this).val()); totalprice += curPrice; // 修正商品名称获取逻辑,直接取当前checkbox后面的label文本 let itemName = $(this).next('label').text(); paypalItem.push({ "unit_amount": {"currency_code": "USD","value": curPrice}, "quantity": 1, "name": itemName }); }); $('#Total').val(totalprice); }); paypal .Buttons({ //Allows you to style the Smart Payment Buttons style: { shape: "rect", color: "gold", layout: "vertical", label: "paypal" }, onInit: function (data, actions) { // Disable the buttons actions.disable(); // Listen for changes from the form input_form.addEventListener("change", function (event) { // Enable or disable the button when condition is met or fails if ( input.value && total.value ) actions.enable(); }); }, // onClick is called when the button is clicked onClick: function () { // Show a validation error if the condition is not met if (!input.value) alert(`请输入您的姓名!`); else if (!total.value) alert("请至少选择一个服务"); }, onError: function (err) { // Alert customer if there is an error alert("出现错误! \n" + err); }, createOrder: function (data, actions) { //Creates the order return actions.order.create({ application_context: { //Disables shipping information shipping_preference: "NO_SHIPPING" }, purchase_units: [ { description: input.value, // 修正为动态取用户输入的姓名 amount: { currency_code: "USD", value: total.value, breakdown: { item_total: { currency_code: "USD", value: total.value }, shipping: { currency_code: "USD", value: 0 } } }, items: paypalItem // 直接取全局维护的商品明细数组 } ] }) } , onApprove: function (data, actions) { return actions.order.capture().then(function (details) { //This code will only trigger if the payment completes successfully //Restarts payment process if customer's payment method is declined if (details.error === "INSTRUMENT_DECLINED") { return actions.restart(); } //Alerts customer of Sucessful Transaction alert( `感谢您的支付 ${details.payer.name.given_name} ${details.payer.name.surname}` ); //Record the details from form into databsae //redirect customer to confirmation page location.href = "https://google.com"; }); } }) .render("#paypal-button-container");
HTML代码(仅修正了input的重复id问题和label的for属性匹配问题)
<div style="display: block; width: 30%;"> <form id="input_form"> <table> <tbody> <tr> <td><input name="on0" type="hidden" value="请选择下方服务:" />请选择下方服务:</td> </tr> <tr> <td> <input type="checkbox" id="service_50" name="service" value="50" > <label for="service_50">$50 per hour</label><br> <input type="checkbox" id="service_60" name="service" value="60" > <label for="service_60">$60.00 Per hour</label><br> <input type="checkbox" id="service_80" name="service" value="80" > <label for="service_80">$80.00 Per hour</label><br> <input type="checkbox" id="service_90" name="service" value="90" > <label for="service_90">$90.00 per hour</label><br> </td> </tr> <tr> <td><input id="Total" type="text" value="" readonly/> :总价格</td> <td><input id="description" type="text" value="" style ="display:none"/></td> <td><input id="amount" type="text" value="" style ="display:none"/></td> </tr> <tr> <td><input name="on1" type="hidden" value="客户姓名" />租车客户姓名</td> </tr> <tr> <td><input maxlength="200" name="os1" id="input" type="text" /></td> </tr> </tbody> </table> </form> </div> <div id="paypal-button-container" style="display: block; width: 30%;"></div> <script src="https://www.paypal.com/sdk/js?client-id=sb¤cy=USD"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
内容的提问来源于stack exchange,提问作者Swapnil Deshmukh
相关产品推荐
相关产品推荐

