我如何总结这个功能而不必为每个按钮重复它?

How can I summarize this function without having to repeat it for each button?

Maybe something that relates the number of the button and the element to add the class
1 = 1
2 = 2
3 = 3
....

<script>
$('.item-carousel.1').click(function() {
  $('.og-expander:not(.og-expander.1)').removeClass('expander-act');
  $('.og-expander.1').toggleClass('expander-act');
  });
  
  $('.item-carousel.2').click(function() {
  $('.og-expander:not(.og-expander.2)').removeClass('expander-act');
  $('.og-expander.2').toggleClass('expander-act');
  });
    
  $('.item-carousel.3').click(function() {
  $('.og-expander:not(.og-expander.3)').removeClass('expander-act');
  $('.og-expander.3').toggleClass('expander-act');
  });

  $('.item-carousel.4').click(function() {
  $('.og-expander:not(.og-expander.4)').removeClass('expander-act');
  $('.og-expander.4').toggleClass('expander-act');
  });  
  <!-- ... -->
  
  </script>

您可以添加一个 for 循环并遍历数组并为每个创建事件侦听器,但最好的选择是为所有相似元素提供相同的 class 并使用 Jquery each function

<script>
const carousel = [1,2,3,4]
for(let i=0,i<carousel.length; i++ ){

$('.item-carousel.'+carousel[i]+').click(function() {
  $('.og-expander:not(.og-expander.'+carousel[i]+')').removeClass('expander-act');
  $('.og-expander.'+carousel[i]+').toggleClass('expander-act');
  });
} 
  <!-- ... -->

  </script>

如果您有 HTML 的后端访问权,您可以设置一个数据标签

<script>
  $('.item-carousel').click(function() {
    var curItem = $(this).data('item')

    $('.og-expander:not(.og-expander.'+curItem+')').removeClass('expander-act');
    $('.og-expander.'+curItem+'').toggleClass('expander-act');
  });
</script>

<div class="item-carousel" data-item="1"></div>
...