[英]Cannot DRY short hand if-else (conditional ternary Operator) in javascript
我有一个简单的html页面,有一个按钮可切换div,但是一切正常,但是我的代码中有一个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');
她是>>>我的傻瓜<<<对此有任何想法吗? 谢谢..
实际上,这是使用此简短if-else语句的正确方法
info.style.display = (info.style.display === '' || info.style.display === 'none') ? 'inline-block' : 'none';
因为您一直在分配,所以只需将条件放在右边; 您也可以(如果确实要使用)使用!info.style.display
而不是info.style.display == ''
:
info.style.display = !info.style.display || info.style.display === 'none' ? 'inline-block' : 'none';
甚至可以利用||
强大的功能||
运算符,尽管我不确定是否会这样做:
info.style.display = (info.style.display || 'none') === 'none' ? 'inline-block' : 'none';
之所以有效,是因为'' || 'none'
'' || 'none'
导致'none'
,但是'anything_else' || 'none'
'anything_else' || 'none'
导致'anything_else'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.