jQuery .click 停止所有具有相同类的元素在单击时打开

jQuery .click stop all elements with the same class opening on click

本文关键字:元素 单击 click jQuery 同类      更新时间:2023-09-26

我编写了这个绑定到按钮的函数,单击该按钮时会切换类以提供下拉列表。唯一的问题是我在同一页面上有多个具有相同功能的按钮,当单击一个按钮时它们都会触发:

任何和所有的帮助都极大地赞赏:)

app.bind.DirectionDropdown = function(){
    
  $('.direction-button').bind('click', function(){
        
    $('.direction-dropdown').toggleClass('active');
	   
  });
  
};
.fade-in {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s,opacity .3s ease-in-out,all .3s ease-in-out;
  -webkit-transition: visibility 0s,opacity .3s ease-in-out,all .3s ease-in-out;
  -ms-transition: visibility 0s,opacity .3s ease-in-out,all .3s ease-in-out;
  -moz-transition: visibility 0s,opacity .3s ease-in-out,all .3s ease-in-out;
}
.active {
  visibility: visible;
  opacity: 1;
  transform: translate(0,0);
  -webkit-transform: translate(0,0);
  -moz-transform: translate(0,0);
  -ms-transform: translate(0,0);
}
<a href="#" title="#" class="direction-button">Click to reveal text</a>
<div class="direction-dropdown fade-in">
<p>Reveal this</p>
</div>
<a href="#" title="#" class="direction-button">Click to reveal text</a>
<div class="direction-dropdown fade-in">
<p>Reveal this</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>

您必须使用 this 关键字,并且仅定位.direction-dropdown 后面的.direction-button

$('.direction-button').on('click', function(){
    $(this).next('.direction-dropdown').toggleClass('active');
});

在你的回调中,你需要使用它而不是.direction-button:

 $('.direction-button').bind('click', function(){
    $(this).toggleClass('active');
 });

$(".direction-button") 使 JQuery 搜索在整个 DOM 对象中