简体   繁体   English

jQuery-单击添加和删除类

[英]JQuery - Add and remove class on click

$('.toggle-button').on('click', function() {
    $('body').addClass('changeCursor');
  });

  $('.toggle-button.toggle-active').on('click', function() {
    $('body').removeClass('changeCursor');
  });

Hey guys I need to add class on body and should remove when again click on it. 大家好,我需要在身体上添加课程,再次单击该课程应删除该课程。 I have attached my code above. 我已经在上面附加了我的代码。 But it's not working please go through for more clarity. 但这不起作用,请仔细阅读。 Thanks :) 谢谢 :)

You can use toggleClass() 您可以使用 toggleClass()

Example: 例:

$('.toggle-button').on('click', function() {
    $('body').toggleClass('changeCursor');
});

Docs: http://api.jquery.com/toggle/ 文件: http//api.jquery.com/toggle/

Check if your body has the class, if not add it, else remove it. 检查您的身体是否有该课程,如果没有,请删除该课程。

$('.toggle-button').on('click', function() {
    if($('body').hasClass('changeCursor')) {
        $('body').removeClass('changeCursor');
    } else {
        $('body').addClass('changeCursor');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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