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

时间:2016-01-29 20:45:31

标签: javascript jquery html css onclick

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

任何和所有帮助都非常适合:)



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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

在你的回调中你需要使用它来代替.direction-button:

 $('.direction-button').bind('click', function(){

    $(this).toggleClass('active');

 });

$(“。direction-button”)在整个DOM对象中进行JQuery搜索

答案 1 :(得分:1)

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

$('.direction-button').on('click', function(){

    $(this).next('.direction-dropdown').toggleClass('active');

});