Here's an example of how to add and remove a class in jQuery based on click events:

$(document).on('click', function(e) {
  if (!$(e.target).closest('.addclass').length) {
    $('.addclass').removeClass('your-class');
  }
});

$('.addclass').on('click', function() {
  $(this).addClass('your-class');
});

In this code:

  • $(document).on('click', function(e) {}): This listens for any click event on the entire document.
  • $(e.target).closest('.addclass').length: This checks if the clicked element (e.target) or any of its parents has the class 'addclass'. If not, it returns 0 (false).
  • $('.addclass').removeClass('your-class'): Removes the class 'your-class' from all elements with the class 'addclass' if the click was outside of them.
  • $('.addclass').on('click', function() {}): This listens for clicks specifically on elements with the class 'addclass'.
  • $(this).addClass('your-class'): Adds the class 'your-class' to the clicked element when it's clicked.

Remember:

  • Replace 'your-class' with the actual class you want to add or remove.

This method provides a simple and efficient way to manage class toggling based on user clicks within your web application.

jQuery: Add Class on Click, Remove if Click Outside

原文地址: https://www.cveoy.top/t/topic/qosB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录