我在我的网站上使用Stripe Checkout,并且使用几个按钮打开Checkout弹出窗口。我现在除了更改id外,基本上使用了完全相同的代码两次。有没有办法将其组合为一个功能?
document.getElementById('buyCourseButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Company name', // TODO
description: 'Product description', // TODO
currency: 'eur',
amount: '{{ course_price }}'
});
e.preventDefault();
});
document.getElementById('buyCourseButton2').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Company name', // TODO
description: 'Product description', // TODO
currency: 'eur',
amount: '{{ course_price }}'
});
e.preventDefault();
});
答案 0 :(得分:2)
const handler = {
open: a => console.log(a)
};
$('#buyCourseButton1,#buyCourseButton2').click(function(e) {
handler.open({
name: 'Company name', // TODO
description: 'Product description', // TODO
currency: 'eur',
amount: '{{ course_price }}'
});
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buyCourseButton1">Button one</button>
<button id="buyCourseButton2">Button two</button>
答案 1 :(得分:0)
给按钮一个类,并使用getElementsByClassName
中的make数组:
const handler = {
open: a => console.log(a)
};
Array.from(document.getElementsByClassName('buyCourseButton')).forEach(function(button) {
button.addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Company name', // TODO
description: 'Product description', // TODO
currency: 'eur',
amount: '{{ course_price }}'
});
e.preventDefault();
});
});
<button class="buyCourseButton">Button one</button>
<button class="buyCourseButton">Button two</button>