if (this.firstChild.style.display == 'none')
{this.firstChild.style.display = 'block'}
else
{this.firstChild.style.display = 'none'};
変数を使用してこのコードを短縮することは可能ですか?
if (this.firstChild.style.display == 'none')
{this.firstChild.style.display = 'block'}
else
{this.firstChild.style.display = 'none'};
変数を使用してこのコードを短縮することは可能ですか?
次のように短縮できます。
var a = this.firstChild.style;
a.display = (a.display=='none'?'block':'none');
var childStyle=this.firstChild.style;
if ( childStyle.display == 'none'){
childStyle.display = 'block';
}
else{
childStyle.display = 'none';
}
同等になります。
次のような三項演算子を使用してさらに短縮できます
var childStyle=this.firstChild.style;
childStyle.display=(childStyle.display=='none')?'block':'none';
これよりも短いjqueryを使用する場合
$("div span:first-child").toggle();
また
$(this).find(">:first-child").toggle();
ところで、これは別の選択肢になるでしょうか?
with this.firstChild.style.display{this=(this=='none')?'block':'none';}
試す:
var elstyle = this.firstChild.style;
elstyle.display = /block/i.test(elstyle.display) ? 'none' : 'block'