2016-08-23 3 views
0

私はHTMLの単純なページを持っていますが、divをトグルしていますが、すべてうまくいきますが、私のコードでif- :javacriptの短い手書きの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'; 

が、あまりにも長い間、おそらく乾燥させることができる、まだ感じのthats、うまく

、私は2つのアプローチを持っていますが、それぞれが正しい方法ではありません。

// 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

この短いのif-else文を使用しての正しい方法である「」|| info.style.display ===" JavaScirptで虚偽。 'info.style.display = info.style.display === '' || info.style.display == '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'となります。空の文字列があるとして、常に第二部をチェックしますnone'`

+0

ありがとう、私の最初の解決策は2回のクリックを必要としますか? –

2

実はこれは `

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

@ T.J.Crowder申し訳ありませんが、あなたのプランナーからのコードを使用しました – Fjallbacka

+0

まあ、私の* plunker ... :-) –

+0

今日私に間違っているxD – Fjallbacka

関連する問題