Conditional jQuery Toggle Function

此生再无相见时 提交于 2019-12-24 17:04:54

问题


I want to hide and show list items based on their attributed class.

The problem is that certain list items have multiple classes. So if I toggle one class then toggle another, any items with both selected classes will be removed.

I created a demo of my problem: http://jsfiddle.net/a4NkN/2/

Here's the JS CODE:

$('#easy').click(function(){
    $(this).toggleClass( "checked" );
    $('.easy').toggle();
});

$('#fun').click(function(){
    $(this).toggleClass( "checked" );
    $('.fun').toggle();
});


$('#silly').click(function(){
    $(this).toggleClass( "checked" );
    $('.silly').toggle();
});

If you select the "Easy" and "Fun" buttons, Boating will disappear.

How can I get Boating to stay?


回答1:


This might be a good point to start from. Although you can do this cheaper and cleaner, that gives the idea:

Use an array to save the status of your selection buttons and one corresponding to hold the class names. Whenever your select buttons get clicked, you set all your elements invisible and reset those visible again, that are already selected by other buttons or the currently clicked, which is all saved in the switcher array.

//saves whether button is active
var switcher = [false, false, false];
//holds your classes selectable
var classes = ['easy', 'fun', 'silly'];

$('.toggler').click(function () {
    // toogle the select button and save status
    var x = $(this).hasClass('checked');
    switcher[$(this).data('switch')] = !x;
    $(this).toggleClass("checked", !x);

    // iterate through your elements to set them active if needed 
    $('li').each(function () {
       var cur = $(this);
       cur.addClass('hidden');
       $.each(switcher, function (index, data) {
          if (data && cur.hasClass(classes[index])) {
             cur.removeClass('hidden');
          }
      });
   });
});

Whole solution in this fiddle: http://jsfiddle.net/BMT4x/




回答2:


You cannot unconditionally toggle elements based on a click on one of the button filters if it is possible for an element to satisfy multiple filters at once. The correct approach is a little more involved.

Since your checked class means that only items corresponding to that button should be shown, do exactly this: toggle them based on the current status of the button. The items should be shown if and only if the corresponding button is checked as a result of clicking it.

$('#easy').click(function(){
    $(this).toggleClass( "checked" );
    $('.easy').toggle($(this).is(".checked"));
});

This code uses the last version of .toggle, the one accepting a boolean argument.

It can also be done more succintly:

$('.easy').toggle($(this).toggleClass( "checked" ).is(".checked"));


来源:https://stackoverflow.com/questions/21269485/conditional-jquery-toggle-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!