如何在不必为每个按钮重复的情况下总结此功能?

问题描述 投票:1回答:2

也许某些东西与按钮的数量和添加类的元素有关 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>
jquery arrays function for-loop click
2个回答
0
投票

你可以添加一个for循环并在数组上循环并为每个创建事件监听器,但最好的选择是给所有相似的元素一个相同的类并使用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>

0
投票

如果您对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>
...
© www.soinside.com 2019 - 2024. All rights reserved.