Значок переключаемого класса элемента, на который нажимается в faq

#javascript #jquery

#javascript #jquery

Вопрос:

Я пытаюсь переключить значок вопроса, как только я нажимаю на него, я почти заставил его работать, значок переключается при нажатии на вопрос и переключается обратно, когда вы снова нажимаете на тот же вопрос.

Это идет не так, когда вы нажимаете на вопрос, а затем на другой вопрос. Первый вопрос, на который вы нажали, автоматически закрывается, но значок не переключается обратно.

 $('.answer').hide();

$('.question').click(function(){
   
    var $this = $(this).parent().find('.answer');
    $(".answer").not($this).hide();
    $this.toggle();
    
    $(this).toggleClass('faqmin')
  
}); 
 * {
  border:0;
  padding:0;
  margin:0;
}

.faq {
  width: 100%;
  padding:10px 0 10px 0;
  border:0;
  border-bottom: 1px solid #e0e0e0;
  outline: none;
  cursor: pointer;
}

.faqplus:after {
  float: right;
  margin-left: 5px;
  content: '02B';
  font-size:18px;
  color: black;
}

.faqmin:after  {
  content: "2212";
}

.answer {
  margin-top:10px;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div> 

Ответ №1:

Вам нужно самостоятельно переключить плюс / минус в другом вопросе:

 $(".faqmin").not(this).toggleClass('faqmin')
 

Обратите внимание, что использование $this для обозначения чего-то другого, чем $(this) может быть очень запутанным, поэтому я изменил эту переменную в приведенном ниже фрагменте.

 $('.answer').hide();

$('.question').click(function(){
   
    var thisans = $(this).parent().find('.answer');
    $(".answer").not(thisans).hide();    
    $(".faqmin").not(this).toggleClass('faqmin')

    thisans.toggle();
    $(this).toggleClass('faqmin')  
}); 
 * {
  border:0;
  padding:0;
  margin:0;
}

.faq {
  width: 100%;
  padding:10px 0 10px 0;
  border:0;
  border-bottom: 1px solid #e0e0e0;
  outline: none;
  cursor: pointer;
}

.faqplus:after {
  float: right;
  margin-left: 5px;
  content: '02B';
  font-size:18px;
  color: black;
}

.faqmin:after  {
  content: "2212";
}

.answer {
  margin-top:10px;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div> 


Примечание: учитывая ваши настройки html, вы можете переключить ответ с помощью css

 $('.question').click(function(){
    $(".faqmin").not(this).removeClass('faqmin');
    $(this).toggleClass('faqmin');
}); 
 * {
  border:0;
  padding:0;
  margin:0;
}

.faq {
  width: 100%;
  padding:10px 0 10px 0;
  border:0;
  border-bottom: 1px solid #e0e0e0;
  outline: none;
  cursor: pointer;
}

.faqplus:after {
  float: right;
  margin-left: 5px;
  content: '02B';
  font-size:18px;
  color: black;
}

.faqmin:after  {
  content: "2212";
}

.answer {
  margin-top:10px;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  display:none;
}
.faqmin   .answer {
  display:block;
  
} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div> 

и если вы добавите стилизованный флажок, вам вообще не нужен js, оставьте его себе.

Комментарии:

1. Нравится вариант less JS! Большое вам спасибо!

Ответ №2:

Когда пользователь нажимает, вам нужно сбросить класс всех вопросов.

https://api.jquery.com/attr/

 $('.answer').hide();

$('.question').click(function(){
    $('.question').attr('class', 'question faqplus'); // here
    var $this = $(this).parent().find('.answer');
    $(".answer").not($this).hide();
    $this.toggle();
    
    $(this).toggleClass('faqmin')
  
}); 
 * {
  border:0;
  padding:0;
  margin:0;
}

.faq {
  width: 100%;
  padding:10px 0 10px 0;
  border:0;
  border-bottom: 1px solid #e0e0e0;
  outline: none;
  cursor: pointer;
}

.faqplus:after {
  float: right;
  margin-left: 5px;
  content: '02B';
  font-size:18px;
  color: black;
}

.faqmin:after  {
  content: "2212";
}

.answer {
  margin-top:10px;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div>

<div class="faq">
  <div class="question faqplus">Question</div>
  <div class="answer">Answer</div>
</div> 

Комментарии:

1. В этом ответе все еще есть небольшая ошибка, когда, если вы снова нажмете на тот же вопрос, значок останется прежним (так что теперь он перевернут). Большое вам спасибо за ваше время, хотя я принял другой ответ из-за версии css с меньшим количеством JS.

2. Нет проблем, наслаждайтесь 🙂