簡體   English   中英

jQuery-切換$(this)上的類並刪除所有其他類

[英]jQuery - Toggle class on $(this) and remove class on all others

這是我正在使用的jQuery代碼段:

$('.panel-title').click(function(){
  $(this).find('.state').toggleClass('rotate');
});

更新 -編輯小提琴以匹配我正在處理的內容

這是一個小提琴,向您展示我在說什么
https://jsfiddle.net/ke1hwn7f/9/

我需要做的是來回切換課程。 這是很直截了當的。 但是我還需要設置它,以便如果該類已經存在於某個元素上,則需要將其刪除。

因此,在小提琴中,您可以看到單擊“ This is heading 4”時,它將切換“ colorChange”類。 但是,然后單擊“這是標題2”,我需要它來切換一個綠色,而且還希望從“這是標題4”(或它可能存在的其他任何地方)中刪除該類,然后再切換剛剛單擊的元素。

我有辦法嗎?

你去了:

$('.panel-title').click(function(){
  // If the clicked element has the rotate class, remove the rotate class from EVERY .panel-title>.state element
  if ($(this).find('.state').hasClass('rotate')){
    $('.panel-title').find('.state').removeClass('rotate');
  }
  // Else, the element doesn't have the rotate class, so we remove it from every element before applying it to the element that was clicked
  else {
    $('.panel-title').find('.state').removeClass('rotate');
    $(this).find('.state').addClass('rotate');
  }
});

如果有該類,則將其刪除到每個標題中,否則,將其刪除至所有標題,然后將其添加到您單擊的標題中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM