2016-11-16 18 views
4

これを検索する方法はわかりませんので、ここで質問しています。Javascriptとjqueryの構文

私はこのコードがどのように機能するかを把握しようとしている:

if ($("#main .oc .dc .image").removeAttr("style"), 1120 > wW && wW > 920) 
    $("#main .oc .dc .image").css({ 
     width: Math.round(.3 * wW) + "px", 
     left: "calc(50% - " + Math.round(.3 * wW/4) + "px)" 
    }); 

私の質問

ある -

.removeAttr("style")1120 > wWの間にカンマがこの文の状態で何をしますか?フィギュアブラケットとCSSプロパティに引用符の欠如前

$("#main .oc .dc .image").css(

- -

そして、どのように正確にアクションが実行されます、

{width:Math.round(.3*wW)+"px",left:"calc(50% - "+Math.round(.3*wW/4)+"px)"} 

は私を混乱させる。私が何か新しいことを学んできた

+2

コンマ演算子は右辺の式を 'if'ステートメントに返します – adeneo

+0

@adeneo true - コンマで区切って指定すると最後の条件だけがチェックされます:https://jsfiddle.net/bgav45wm /。 –

+0

@RoryMcCrossan - もっとも確かに、その属性をそのように削除する理由はなく、 'if'条件の前に自分の行を置くことができ、誰かが単に"賢い " 。 – adeneo

答えて

2

質問のおかげで、m個のaksem ...
や説明のためのおかげで、@vlaz ...


私はこのthrought行くためにテストスニペットを作っ:

var wW = 1000; 
 

 
$("#test1").on("click",function(){ 
 
    if ($("#main .oc .dc .image").removeAttr("style"), 1120 > wW && wW > 920) 
 
     $("#main .oc .dc .image").css({ 
 
      width: Math.round(.3 * wW) + "px", 
 
      left: "calc(50% - " + Math.round(.3 * wW/4) + "px)" 
 
     }); 
 
}); 
 

 
$("#test2").on("click",function(){ 
 
    if (1120 > wW && wW > 920) 
 
     $("#main .oc .dc .image").css({ 
 
      width: Math.round(.3 * wW) + "px", 
 
      left: "calc(50% - " + Math.round(.3 * wW/4) + "px)" 
 
     }); 
 
}); 
 

 
$("#test3").on("click",function(){ 
 
    if (false, 1120 > wW && wW > 920) 
 
     $("#main .oc .dc .image").css({ 
 
      width: Math.round(.3 * wW) + "px", 
 
      left: "calc(50% - " + Math.round(.3 * wW/4) + "px)" 
 
     }); 
 
});
.image{ 
 
    border:1px solid black; 
 
    width:50%; 
 
    position:absolute; 
 
    left:20px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="main"> 
 
    main 
 
    <div class="oc"> 
 
     oc 
 
     <div class="dc"> 
 
      dc 
 
      <div class="image" style="color:red;"> 
 
       image 
 
      </div> 
 
     </div> 
 
    </div> 
 
</div> 
 
<br> 
 
<br> 
 
<input type="button" id="test1" value="Test 1 - Execute full condition"><br> 
 
<input type="button" id="test2" value="Test 2 - Execute condition without the left hand part"><br> 
 
<input type="button" id="test3" value="Test 3 - Execute condition with a FALSE in the left hand part"><br>

そうなことが条件で二つの引数、昏睡分離が存在することです。
もっとあるかもしれません。

"テスト1"では、左手条件が実行されます(インラインスタイル属性ISで定義された赤色)が、ifステートメントでは真であるブール結果は考慮されません。

最後の条件のみになります。
「テスト3」は、左手の状態がfalseであることを証明しています。

右手の状態をtrueと評価する(したがってその効果を参照)ように、wWを1000と定義しました。
.imageのCSS position:absoluteも定義しました。

この「トリック」が可読性を大幅に低下させるという事実については、@ Jason Pに同意します。
私は有用な場合は表示されません。それでも、知ることは良いことです!