首页 > 解决方案 > 避免 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();
});

标签: javascriptjquery

解决方案


您可以使用jquery-multiple-selector

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>


推荐阅读