javascript - 避免 JavaScript 函数中的重复代码
问题描述
我在我的网站上使用 Stripe 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();
});
解决方案
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>
推荐阅读
- excel - 如何复制隐藏的工作表并且新复制的工作表不隐藏?
- python - 我无法使用 Django-Rest-Framework 注册用户
- php - 一种在 PHP 中折叠对象数组的简写方法
- c - C是整数数学等价于无符号数学?
- python - 为什么我的 fastapi 或 uvicorn 会被关闭?
- python - 如何在 VS Code 终端中从 .py 文件运行多个 django python 脚本?
- certificate - 使用 HyperLedger Fabric 证书签署消息
- php - PHP中列的总和给出错误的输出
- r - 合并大型数据集
- css - CSS 背景 url 图像在较大的分辨率下看起来很模糊,但在较小的屏幕分辨率下看起来很清晰