📜  jquery if class clicked - Javascript(1)

📅  最后修改于: 2023-12-03 15:32:08.477000             🧑  作者: Mango

jQuery if Class Clicked

If you are working with jQuery and need to add or remove a class on click, there is a simple way to accomplish this with the use of if statements.

Adding a Class on Click

To add a class when an element is clicked, you can use the .click() function in jQuery. Here is an example:

$('.btn').click(function() {
  $(this).addClass('active');
});

In this example, when an element with the class .btn is clicked, the active class will be added to that element.

Removing a Class on Click

To remove a class when an element is clicked, you can use the .click() function in jQuery along with the .removeClass() function. Here is an example:

$('.btn').click(function() {
  $(this).removeClass('active');
});

In this example, when an element with the class .btn is clicked, the active class will be removed from that element.

Checking if an Element has a Class

To check if an element has a specific class before adding or removing it, you can use the .hasClass() function in jQuery. Here is an example:

$('.btn').click(function() {
  if ($(this).hasClass('active')) {
    $(this).removeClass('active');
  } else {
    $(this).addClass('active');
  }
});

In this example, when an element with the class .btn is clicked, it will check if the element has the active class. If it does, the active class will be removed. If it doesn't, the active class will be added.

Conclusion

Using if statements with jQuery's .click() function is a simple way to add or remove classes on click. With the help of the .hasClass() function, you can also check if an element has a specific class before adding or removing it.