将变量从HTML传递到使用addEventListener的Javascript文件



我使用Stripe接受Apple pay支付(这里不是特别重要)。我用的是Django。代码可以很好地处理付款,但是我在将变量传递给我单独的.js文件时遇到了麻烦。(金额收费)从我的HTML文件到实际处理支付的Javascript文件。

home。

{% load static %}
<!DOCTYPE html>
<html>
<head>
import more scripts here
<script src="https://js.stripe.com/v3/"></script>
<script src="{% static 'interface/utils.js' %}" defer></script>
<script src="{% static 'interface/apple-pay.js' %}" defer></script>
</head>
<body>
<header class="text-center">
<div id="rectangle"></div>
</header>
<section>
<div class="text-center">
<div class="container container--narrow">
<script>amount=parseInt("{{event.price}}")</script>
<div id="payment-request-button">
<!-- A Stripe Element will be inserted here if the browser supports this type of payment method. -->
</div>
</div>            
</div>
</section>
</body>
</html>

用来处理支付的Javascript文件:apple-pay.js

document.addEventListener('DOMContentLoaded', async () => {
const stripe = Stripe('pk_test_testkey');
const paymentRequest = stripe.paymentRequest() ({
currency: 'usd',
country: 'US',
requestPayerName: true,
requestPayerEmail: true,
total: {
label: 'Test payment',
amount: amount, //trying to pass the variable in here
}
});
// Other functions that get called go here
});

我在控制台中看到的错误是API调用中的'total'不再是对象。Console.log(typeof amount)返回一个数字,Console.log(amount)返回我期望的数字。但如何将其传递给Javascript文件呢?

使用data属性。你目前的做法理论上是可行的,如果你做得恰到好处,但这绝对不是最好的做法。一个简单的解决方案是:

代替这段代码
<script>amount=parseInt("{{event.price}}")</script>

只是将data-amount属性附加到树附近的元素。你甚至可以像这样把它放在payment-request-button上:

<div id="payment-request-button" data-amount="{{event.price}}">

然后在javascript中:

//...
amount: parseInt(document.querySelector("#payment-request-button").dataset.amount)
//...

如果你不能编辑javascript文件,那么事情要复杂得多,所以我希望你可以!

最新更新