2016-08-23 91 views
0

我有一个简单的HTML页面有一个按钮切换div ,,但一切工作正常,但我有我的代码中的if-else语句像这样:不能在JavaScript干短手if-else(条件三元运算符)

if (info.style.display === '' || info.style.display == 'none'){ 
    info.style.display = 'inline-block'; 
} else { 
    info.style.display = 'none'; 
} 

我已经决定使用这样的简短语句;

info.style.display === ''||info.style.display ==='none' ? info.style.display = 'inline-block' :info.style.display = 'none'; 

,但仍然感觉这就是太长,大概可以干燥,

嗯,我有两种方法,但每个都是不正确的做法:

// this solution works but requires two clicks first time run: 

info.style.display ==(''||'none') ?info.style.display = 'inline-block' :info.style.display = 'none'; 

和:

// this solution doesn't work: 
    info.style.display == (''||'none' ? 'inline-block' : 'none'); 

她是>>> My Plunker <<< 对此有任何想法吗? 谢谢..

+1

'“” || info.style.display ==='的正确途径none''会经常检查第二部分为空字符串JavaScirpt中的虚假。 'info.style.display = info.style.display ===''|| info.style.display =='none'? 'inline-block':'none';' – Tushar

+0

你应该尝试在一个临时变量中存储'info.style'或甚至'info.style.display' – Bergi

回答

2

既然你总是分配,就把条件放在右边;你也可以(如果你真的想)使用!info.style.display代替info.style.display == ''

info.style.display = !info.style.display || info.style.display === 'none' ? 'inline-block' : 'none'; 

甚至采取curiously-powerful || operator的优势,虽然我不知道我会做到这一点:

info.style.display = (info.style.display || 'none') === 'none' ? 'inline-block' : 'none'; 

那因为'' || 'none'结果在'none',但'anything_else' || 'none'结果在'anything_else'

+0

谢谢,任何想法为什么我的第一个解决方案需要两次点击? –

2

其实这是用这短短的if-else语句

info.style.display = (info.style.display === '' || info.style.display === 'none') ? 'inline-block' : 'none'; 
+0

@ T.J.Crowder对不起,我使用了你的朋友的代码 – Fjallbacka

+0

嗯,不是*我的* plunker ... :-) –

+0

我今天怎么了xD – Fjallbacka