开发者

Help me optimize the if else in JavaScript (jQuery)

Is it possible to somehow shorten this code:

var i=GetStringFromServer('/url');
if(i){
   $('#Div1').hide();
   $('#Div2').show();
}
else{
   $('#Div1).show();
   $('#Div2).hide();
}

In C# I'd simply do this:

bool smth=GetBool();
_el1.Visible=smth;
_el2.Visible=!smth;

Is it possible to mimick the logic in JavaScript?

UPDATE: Thank you guys for nice answers, I peeked at toggle myself before asking but what confused was the method signature:

toggle(fn1, fn2);

I thought that function expected some tricky callbacks but apparently it's flexible enough to handle bo开发者_开发问答th plain booleans and callbacks.

UPDATE2: Thanks to Robert's and Fabien's comments, the true answer was finally found. Toggle will always make elements visible or invisible based on evaluating the argument to bool.


$('#Div1, #Div2').toggle(i);


If you give toggle a boolean argument, it will apply that to every matched element. From the docs:

Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).

So in your case, you want:

$("#Div1").toggle(!i);
$("#Div2").toggle(i);


var i=GetStringFromServer('/url');

$('#Div1').toggle(!i);
$('#Div2').toggle(i);

But you may have problem to get the i var if you do it this way as it looks like you are using Ajax.


It's probably fine as it is, but you could do this if you like:

var i=GetStringFromServer('/url');
$('#Div1')[i  ? 'hide' : 'show']();
$('#Div2')[!i ? 'hide' : 'show']();

I don't think you get much out of it in terms of space savings or runtime, and it's a lot less clear to future code maintainers.


In addition to the other answers, if you can't toggle, but need to show/hide explicitly:

var divs = ['#div1', '#div2'],
    j = (i ? 1 : 0)
$(divs[1 - j]).show()
$(divs[j]).hide()


I'm used to do like this:

  if($('#Div1').css("display") == "none")
     {
       $(this).show(); 
     }
     else
     {
       $(this).hide(); 
     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜