简体   繁体   中英

how to block toggle class when classe is on

I am using several anchors and when clicking on an anchor, the class switches to img-swap on If I click on another anchor, the class of that anchor switches also on on What I want to achieve: if 1 anchor has already the class on on , all other anchors must be blocked to switch on on

jQuery(document).ready(function ($) {
 $('a.img-swap').click(function () {
  $(this).toggleClass('on');
 }); 
});

Is this possible to do a check in javascript when a class is on on and if so, block the other anchors to switch from class?

I would just bind handler to be fired only once:

 
 
 
  
  jQuery(document).ready(function ($) { $('a.img-swap').one('click', function () { $(this).toggleClass('on'); }); });
 
  

Now if you want state on to be switchable, i'd use instead:

jQuery(document).ready(function ($) {
 $('a.img-swap').click(function () {
  if($('a.img-swap.on').not(this).length) return;
  $(this).toggleClass('on');
 }); 
});

Try This -

 $(document).ready(function() { $("a.img-swap").click(function() { $("a.img-swap").each(function() { if ($(this).hasClass("on")) $(this).removeClass("on"); }); $(this).addClass("on"); }); }); 
 .on { background: #ff0000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <a class="img-swap on"> Img1 </a> <a class="img-swap"> Img1 </a> <a class="img-swap"> Img1 </a> <a class="img-swap"> Img1 </a> 

Use hasClass to check if element has a class.

jQuery(document).ready(function ($) {
    $('a.img-swap').click(function () {
        if(!$("a.img-swap").hasClass("on"))
            $(this).toggleClass('on');
    });
});

 $(document).ready(function () { $('a.img-swap').click(function () { if($(".on").length > 0 ){ console.log("Found"); }else{ console.log("not found"); $(this).addClass('on') } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class='img-swap'>abcd1</a> <a class='img-swap'>abcd2</a> <a class='img-swap'>abcd3</a> <a class='img-swap'>abcd4</a> <a class='img-swap'>abcd5</a> <a class='img-swap'>abcd6</a> 

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