2016-09-29 2 views
0

У меня возникает проблема, когда я не могу отфильтровать, если ранее я выбрал значение сортировки. Я хочу только сортировать видимые элементы, но когда я выбираю другой параметр фильтра, фильтр не обновляется. Любые предложения будут ценны. спасибо большоеСписок сортировки и фильтра JQuery

вот мои ЯШ:

// Filtering plans options 
$('.js-filter-options li a').click(function() { 

    // looks for the class of the clicked options 
    var allPlans = $(this).attr('class'); 
    // reset the active class on all the options 
    $('.js-filter-options li, .js-input-check').removeClass('active'); 
    // update the active state on clicked option 
    $(this).parent().addClass('active'); 
    $(this).children().toggleClass('active'); 

    if(allPlans == 'js-all-plans') { 
     // show all the plans 
     $('.js-filter-results').find('section.js-filter-results-plans').show(); 
    } 
    else { 
     // hide plans that don't match class 
     $('.js-filter-results').find('section:not(.' + allPlans + ')').hide(); 
     // show plans that are match class 
     $('.js-filter-results').find('section.' + allPlans).show(); 
    } 
});//end 

//Dropdown options filtering 
$('.js-dropdown-filter').change(function() { 
    var $filterList = $('.js-filter-results-plans:visible'); 

    // Do something for option price lowest to highest 
    if ($(this).val() === 'low-high') { 
     var lowHigh = $filterList.sort(function (a, b) { 
      return $(a).find('.price__amount').text() > $(b).find('.price__amount').text(); 
     }); 
     $('.js-filter-results').html(lowHigh); 

    } 
    // Do something for option price highest to lowest 
    else if ($(this).val() === 'high-low') { 
     var highLow = $filterList.sort(function (a, b) { 
      return $(a).find('.price__amount').text() < $(b).find('.price__amount').text(); 
     }); 
     $('.js-filter-results').html(highLow); 
    } 
    // Do something for option popular 
    else { 
     var popular = $filterList.sort(function (a, b) { 
      return $(a).data("order")-$(b).data("order"); 
     }); 
     $('.js-filter-results').html(popular); 
    } 
});//end 

FIDDLE: https://fiddle.jshell.net/tLLfkg5w/

ответ

0

Если я все еще недопонимание вас, проблема, как представляется, эта строка:

var $filterList = $('.js-filter-results-plans:visible'); 


Когда применяется ваш фильтр «1» или «2», :visible обеспечивает запуск $filterList который содержит только два элемента, когда я считаю, что вы хотите, чтобы он содержал все четыре элемента. Так, в приведенном ниже фрагменте кода, я удалил :visible:

var $filterList = $('.js-filter-results-plans'); 


UPDATE: Я собирался упомянуть parseInt, но ты меня опередил. Кроме того, неправильная сортировка не вызвана отсутствием :visible, это связано с тем, что строки return в ваших численных сортировках неверны. См. Измененный фрагмент ниже. Опять же, пожалуйста, дайте мне знать, дает ли фрагмент желаемое поведение.

// Filtering plans options 
 
$('.js-filter-options li a').click(function() { 
 

 
    // looks for the class of the clicked options 
 
    var allPlans = $(this).attr('class'); 
 
    // reset the active class on all the options 
 
    $('.js-filter-options li, .js-input-check').removeClass('active'); 
 
    // update the active state on clicked option 
 
    $(this).parent().addClass('active'); 
 
    $(this).children().toggleClass('active'); 
 
    
 
    if(allPlans == 'js-all-plans') { 
 
     // show all the plans 
 
     $('.js-filter-results').find('section.js-filter-results-plans').show(); 
 
    } 
 
    else { 
 
     // hide plans that don't match class 
 
     $('.js-filter-results').find('section:not(.' + allPlans + ')').hide(); 
 
     // show plans that are match class 
 
     $('.js-filter-results').find('section.' + allPlans).show(); 
 
    } 
 
});//end 
 

 
//Dropdown options filtering 
 
$('.js-dropdown-filter').change(function() { 
 
    // var $filterList = $('.js-filter-results-plans:visible'); 
 
    var $filterList = $('.js-filter-results-plans'); 
 

 
    // Do something for option price lowest to highest 
 
    if ($(this).val() === 'low-high') { 
 
     var lowHigh = $filterList.sort(function (a, b) { 
 
      return parseInt($(a).find('.price__amount').text()) - parseInt($(b).find('.price__amount').text()); 
 
     }); 
 
     $('.js-filter-results').html(lowHigh); 
 

 
    } 
 
    // Do something for option price highest to lowest 
 
    else if ($(this).val() === 'high-low') { 
 
     var highLow = $filterList.sort(function (a, b) { 
 
      return parseInt($(b).find('.price__amount').text()) - parseInt($(a).find('.price__amount').text()); 
 
     }); 
 
     $('.js-filter-results').html(highLow); 
 
    } 
 
    // Do something for option popular 
 
    else { 
 
     var popular = $filterList.sort(function (a, b) { 
 
      return $(a).data("order")-$(b).data("order"); 
 
     }); 
 
     $('.js-filter-results').html(popular); 
 
    } 
 
});//end
.h-hidden { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 

 
<ul class="js-filter-options"> 
 

 
    <li><a href="#" class="js-1-plan">1</a></li> 
 

 
    <li><a href="#" class="js-2-plan">2</a></li> 
 

 
    <li><a href="#" class="js-3-plan">3</a></li> 
 

 
    <li><a href="#" class="js-4-plan">4</a></li> 
 

 
</ul><!--/.js-filter-options --> 
 
    
 
<select class="js-dropdown-filter"> 
 

 
    <option value="popular">Popular</option> 
 

 
    <option value="high-low">Price Highest to Lowest</option> 
 

 
    <option value="low-high">Price Lowest to Highest</option> 
 

 
</select><!--/.js-dropdown-filter --> 
 

 
<section class="js-filter-results"> 
 

 
    <section class="js-filter-results-plans js-1-plan" data-order="1"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">24</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 

 
    <section class="js-filter-results-plans js-1-plan" data-order="2"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">34</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 
    
 
    <section class="js-filter-results-plans js-1-plan" data-order="3"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">33</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 
    
 
    <section class="js-filter-results-plans js-1-plan" data-order="4"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">92</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 

 
    <section class="js-filter-results-plans js-2-plan h-hidden" data-order="1"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">44</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 

 
    <section class="js-filter-results-plans js-2-plan h-hidden" data-order="2"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">55</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 

 
    <section class="js-filter-results-plans js-3-plan h-hidden" data-order="1"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">66</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 
    
 
    <section class="js-filter-results-plans js-3-plan h-hidden" data-order="2"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">42</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 

 
    <section class="js-filter-results-plans js-3-plan h-hidden" data-order="3"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">109</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 
    
 
    <section class="js-filter-results-plans js-3-plan h-hidden" data-order="3"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">57</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 

 
    <section class="js-filter-results-plans js-4-plan h-hidden" data-order="1"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">19</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 
    
 
    <section class="js-filter-results-plans js-4-plan h-hidden" data-order="2"> 
 

 
    <div class="price"> 
 

 
     <span class="price__amount">11</span> 
 

 
    </div><!--/.price --> 
 

 
    </section><!--/.js-filter-results-plans --> 
 
    
 
</section><!--/.js-filter-results -->

+0

Привет MJH, спасибо за ваш ответ. Я обновил свою скрипку, но проблема, с которой я сталкиваюсь (вы можете видеть ее в скрипке), заключается в том, что при загрузке фильтры и параметры сортировки работают нормально, если вы не переключаете номер фильтра (1, 2, 3, 4 - в моя скрипка я только добавил содержимое к вариантам 1 и 2). Он работает, если вы просто оставите параметр сортировки самым популярным, но если вы отсортируете его, нажав любую из двух других и перейдите к фильтру номер 2, он ничего не отобразит. Я не уверен, что случилось с моим скриптом. Вы можете мне помочь? Большое вам спасибо https://fiddle.jshell.net/obnbjf3t/ – tiffsaw

+0

спасибо за ваш ответ. Я пробовал это раньше, но проблема в том, что он не просто сортирует отфильтрованный список, а сортирует весь список, что означает, что при сортировке порядок неправильный. вы можете увидеть это на этой скрипке, я добавил дополнительные параметры, и он не сортируется правильно. Есть ли у вас другие предложения? Я хотел бы отсортировать список видимых фильтров, и при нажатии на другой фильтр он отображает конкретный список с указанной сортировкой. https://fiddle.jshell.net/9qe0z9mb/ Я очень ценю вашу помощь – tiffsaw

+0

Пожалуйста, см. мой пересмотренный ответ. – MJH

Смежные вопросы