How to install jquery.show/.hide without repeating div selectors

I want to pass this function True or False and show the listed elements (true) or hide (false) at this input.

I am currently using this feature ...

        function SetElementVisibility(visible) {
        if (visible) {
            $("#Div1").show("slow");
            $("#Div2").show("slow");
            $("#Div3").show("slow");
        }
        else {
            $("#Div1").hide("slow");
            $("#Div2").hide("slow");
            $("#Div3").hide("slow");
        }
    }

But I would rather not repeat myself, naming a Div for each result.

How can I reorganize this into more DRY (don't repeat myself)?

Thanks Cohan

+3
source share
8 answers

Use quadratic notation to select a method name depending on a variable visible:

$('#Div1, #Div2, #Div3')[visible? 'show' : 'hide']('slow');
+8
source

This should work:

function SetElementVisibility(visible) {
   $("#Div1,#Div2,#Div3")[visible]("slow");
}

// Display all
SetElementVisibility( "show" );

// Hide all
SetElementVisibility( "hide" );

"show" "hide" , true false, :

function SetElementVisibility(visible) {
   $("#Div1,#Div2,#Div3")[visible?'show':'hide']("slow");
}

// Display all
SetElementVisibility( true );

// Hide all
SetElementVisibility( false );
+6

:

$("ID").toggle()

id. :

function SetElementVisibility(visible) {
    if (visible) {
        $(".showHideDiv").show("slow");
    }
    else {
        $(".showHideDiv").hide("slow");
    }
}
+1

if(..)
$('[id^=Div]').show();
else
$('[id^=Div]').hide();

div id!

+1

$( "# Div1, # Div2, # Div3" ). show (...

.

+1

:

$('#Div1, #Div2, #Div3').hide('slow');

$('#Div1').add('#Div2').add('#Div3').hide('slow');

$.each(['#Div1', '#Div2', '#Div3'], function(i,v){
    $(v).hide('slow');
});

, , .

divs Div,

$('div[id=^Div]').hide('slow');
+1

:

function SetElementVisibility(visible) {
    $elements =  $("#Div1, #Div2, #Div3");
    if (visible) {
        $elements.show("slow");
    }
    else {
        $elements.hide("slow");
    }
}
0

,

 function SetElementVisibility() {
       $('#Div1,#Div2,#Div3').toggle();
}
0

Source: https://habr.com/ru/post/1753528/


All Articles