简体   繁体   中英

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

I have written this function that binds to a button, which when clicked toggles the class to provide a dropdown. The only problem is is that I have multiple buttons on the same page that have the same functionality, and they all fire when one is clicked:

Any and all help greatly appricated :)

 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> 

In your callback you need to use this instead of .direction-button:

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

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

 });

$(".direction-button") makes JQuery search in the entire DOM object

You have to use the this keyword, and target only the .direction-dropdown following the .direction-button

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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM