2015-10-20 6 views
0

Я пытаюсь создать простой переключатель для 3 групп списков с несколькими элементами списка в каждом. Каждая группа списка может иметь только один активный элемент за один раз, в общей сложности 3 активных элемента (по одному в группе списка).Как перебирать группы списков независимо друг от друга

Мой код только деактивирует активный класс группы списка в последней группе списка, что мне не хватает?

См JSbin: https://jsbin.com/hizezu

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

HTML

     <div id="selectPatientCategories"> 
          <div class="list-group"> 
           <h4>Select Doctor</h4> 
           <hr> 
           <a href="#" class="list-group-item">Dr. Justice Freedom</a> 
           <a href="#" class="list-group-item">Dr. Martin Fabio</a> 
           <a href="#" class="list-group-item">Dr. Jenny Walter</a> 
           <a href="#" class="list-group-item">Dr. Loius Von Winkle</a> 
           <a href="#" class="list-group-item">Dr. Mary McDoctors</a> 
           <a href="#" class="list-group-item">Dr. Freethinker Liver</a> 
           <a href="#" class="list-group-item">Dr. Cognitive Thinker</a> 
          </div> 
         <div class="list-group"> 
           <h4>Select Doctor</h4> 
           <hr> 
           <a href="#" class="list-group-item">Dr. Justice Freedom</a> 
           <a href="#" class="list-group-item">Dr. Martin Fabio</a> 
           <a href="#" class="list-group-item">Dr. Jenny Walter</a> 
           <a href="#" class="list-group-item">Dr. Loius Von Winkle</a> 
           <a href="#" class="list-group-item">Dr. Mary McDoctors</a> 
           <a href="#" class="list-group-item">Dr. Freethinker Liver</a> 
           <a href="#" class="list-group-item">Dr. Cognitive Thinker</a> 
          </div> 
        <div class="list-group"> 
           <h4>Select Doctor</h4> 
           <hr> 
           <a href="#" class="list-group-item">Dr. Justice Freedom</a> 
           <a href="#" class="list-group-item">Dr. Martin Fabio</a> 
           <a href="#" class="list-group-item">Dr. Jenny Walter</a> 
           <a href="#" class="list-group-item">Dr. Loius Von Winkle</a> 
           <a href="#" class="list-group-item">Dr. Mary McDoctors</a> 
           <a href="#" class="list-group-item">Dr. Freethinker Liver</a> 
           <a href="#" class="list-group-item">Dr. Cognitive Thinker</a> 
          </div> 
         </div> 

И JS

// Vanilla JS version of apply class "active" on click of .list-group-item 

    var listGroup = document.querySelectorAll('#selectPatientCategories .list-group'); 
    //console.log(listGroup); 

    var cats = document.querySelectorAll('a.list-group-item'); 
    //console.log(cats); 

    // For each category list group 
    var listGroupIndex = 0, listGroupLength = listGroup.length; 
    for (; listGroupIndex < listGroupLength; listGroupIndex++) { 
     var thisListGroup = listGroup[listGroupIndex]; 
     //console.log(thisListGroup); 

     // For each category list item 
     var catIndex = 0, catLength = cats.length; 
     for (; catIndex < catLength; catIndex++) { 
      var thiscat = cats[catIndex]; 
      //console.log(listGroupIndex); 

      // Click function on list item 
      thiscat.addEventListener('click', function() { 
       //console.log(thisListGroup); 

       var thisListGroupCats = thisListGroup.querySelectorAll('a.list-group-item'); 
       //console.log(thisListGroupCats); 

       var rmcatIndex = 0, rmCatLength = thisListGroupCats.length; 
       //console.log(rmCatLength); 
       for (; rmcatIndex < rmCatLength; rmcatIndex++) { 

        rmthiscat = thisListGroupCats[rmcatIndex]; 
        //console.log(rmthiscat); 

        rmthiscat.classList.remove('active'); 
        this.classList.add('active'); 

       } 

      }); // End click function 
     } 
    } 
+0

Почему ты меченый JQuery? – DontVoteMeDown

+0

Ищете ответ на ванильный javascript, но также открываем для jQuery версии – TetraDev

ответ

2

Я думаю, что вы переусердствовали за то, что необходимо с вашей текущей реализации. Все, что вам нужно, это просто выполнить итерацию текущей группы-списка и для каждого 'a' удалить класс 'active', а затем добавить класс 'active' к элементу, который был нажат.

// target an 'a' element with class='list-group-item' inside an element which has class 'list-group'. 
$(".list-group a[class='list-group-item']").click(function() 
{ 
    // get the 'list-group' element of the current 'a' element clicked. 
    // $(this) refers to the element object which invoked the event. 
    var listGroup = $(this).parent(); 
    // look for each 'a' element within the current 'list-group' and remove class 'active' if it has so. 
    $(listGroup).find("a").removeClass("active"); 

    // add class 'active' to the 'a' element which was clicked 
    $(this).addClass("active"); 
}); 

Пример: http://jsfiddle.net/j2c59j9j/2/

+0

Вы можете заменить свой 'each' этой' $ (listGroup) .find («a»). RemoveClass («active») ' – DontVoteMeDown

+0

Правильно. Спасибо что подметил это. Обновлен код. – DinoMyte

+0

Спасибо за помощь. Основываясь на вашем ответе, я смог создать версию vanilla js, которая также работает. – TetraDev

0

Я создал чистый яваскрипта решение, основанное на ответ DinoMyte в: https://jsbin.com/vexoli

//Vanilla JS version of apply class "active" on click of .list-group-item 

    var listGroup = document.querySelectorAll('#selectPatientCategories .list-group'); 
    //console.log(listGroup); 

    var cats = document.querySelectorAll('a.list-group-item'); 
    //console.log(cats); 

    // For each category list item 
    var catIndex = 0, catLength = cats.length; 
    for (; catIndex < catLength; catIndex++) { 
     var thiscat = cats[catIndex]; 
     //console.log(listGroupIndex); 

     // Click function on list item 
     thiscat.addEventListener('click', function() { 
      //console.log(thisListGroup); 

      //Get the parent .list-group 
      thisListGroup = this.parentElement; 
      thisListGroupCats = thisListGroup.querySelectorAll('a.list-group-item'); 

      //console.log(thisListGroupCats); 

      // For each category .list-group-item within this listGroup 
      var listGroupIndex = 0, listGroupCatsLength = thisListGroupCats.length; 
      for (; listGroupIndex < listGroupCatsLength; listGroupIndex++) { 

       // Focus on just this .list-group being iterated 
       rmThisCat = thisListGroupCats[listGroupIndex]; 
       rmThisCat.classList.remove('active'); 

      } 
      this.classList.add('active'); 

     }); // End click function 
    } 
Смежные вопросы