i have a simple page of html has a button toggles a div,, however all is working fine but i have an if-else statement in my code like this:
if (info.style.display === '' || info.style.display == 'none'){
info.style.display = 'inline-block';
} else {
info.style.display = 'none';
}
I`m have decided to use short hand statement like so;
info.style.display === ''||info.style.display ==='none' ? info.style.display = 'inline-block' :info.style.display = 'none';
but still feeling thats too long and probably can be dried,
well, i have two approaches but each is not the right way:
// this solution works but requires two clicks first time run:
info.style.display ==( ''||'none' ) ?info.style.display = 'inline-block' :info.style.display = 'none';
and :
// this solution doesn't work:
info.style.display == (''||'none' ? 'inline-block' : 'none');
Her is >>> My Plunker <<< Any idea on this please? Thank you..
实际上,这是使用此简短if-else语句的正确方法
info.style.display = (info.style.display === '' || info.style.display === 'none') ? 'inline-block' : 'none';
Since you're always assigning, just put the conditional on the right; you can also (if you really want to) use !info.style.display
instead of info.style.display == ''
:
info.style.display = !info.style.display || info.style.display === 'none' ? 'inline-block' : 'none';
Or even taking advantage of the curiously-powerful ||
operator though I'm not sure I'd do it:
info.style.display = (info.style.display || 'none') === 'none' ? 'inline-block' : 'none';
That works because '' || 'none'
'' || 'none'
results in 'none'
, but 'anything_else' || 'none'
'anything_else' || 'none'
results in 'anything_else'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.