2016-11-16 76 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之间的逗号在这个语句的条件呢?

,这也正是行动执行后, -

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

图支架以及缺乏行情的之前,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

谢谢了问题,男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

请注意,我将wW定义为1000,以便使右手条件评估为true(因此请参阅效果)。
我还为.image定义了一个CSS position:absolute

我同意@Jason P关于这个“技巧”降低了可读性的事实。
我没有看到任何有用的情况。不过,知道这件事是一件好事!