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
Use quadratic notation to select a method name depending on a variable visible:
visible
$('#Div1, #Div2, #Div3')[visible? 'show' : 'hide']('slow');
This should work:
function SetElementVisibility(visible) { $("#Div1,#Div2,#Div3")[visible]("slow"); } // Display all SetElementVisibility( "show" ); // Hide all SetElementVisibility( "hide" );
"show" "hide" , true false, :
"show"
"hide"
true
false
function SetElementVisibility(visible) { $("#Div1,#Div2,#Div3")[visible?'show':'hide']("slow"); } // Display all SetElementVisibility( true ); // Hide all SetElementVisibility( false );
:
$("ID").toggle()
id. :
function SetElementVisibility(visible) { if (visible) { $(".showHideDiv").show("slow"); } else { $(".showHideDiv").hide("slow"); } }
if(..) $('[id^=Div]').show(); else $('[id^=Div]').hide();
div id!
$( "# Div1, # Div2, # Div3" ). show (...
.
$('#Div1, #Div2, #Div3').hide('slow');
$('#Div1').add('#Div2').add('#Div3').hide('slow');
$.each(['#Div1', '#Div2', '#Div3'], function(i,v){ $(v).hide('slow'); });
, , .
divs Div,
divs
Div
$('div[id=^Div]').hide('slow');
function SetElementVisibility(visible) { $elements = $("#Div1, #Div2, #Div3"); if (visible) { $elements.show("slow"); } else { $elements.hide("slow"); } }
,
function SetElementVisibility() { $('#Div1,#Div2,#Div3').toggle(); }
Source: https://habr.com/ru/post/1753528/More articles:HTML / CSS: how to make sidebar and content follow each other - htmlПочему HTC Droid не работает с OTA 2.1 для связи с RFCOMM? - androidAndroid Retry / Cancel Dialog - androidHow to convert "¢ ÐμÑ" (this is a Russian word) into something readable? - phpIs there an iCal API for iPhone OS4 - objective-cItemDataBound 'e.item.dataitem ("key") with ListView control - vb.netAutomatically resize columns when elements are expanded - javaКак получить данные checkbox с помощью python на gae - pythoniPhone enumerateGroupsWithTypes finish selector - iphoneHibernation criteria - return parent records that have child records - javaAll Articles