obm*_*mon 1 javascript shorthand
我正在努力提高我的编码技能,但我似乎无法弄清楚这一点.如何以速记书写以下内容?
/* fade */
$('.toggle-ui').on({
'click': function (e) {
e.preventDefault();
var divToFade = ['#logo', '#hide-interface'];
$.each(divToFade, function(intValue, currentElement) {
// check alpha state and switch
var currOp = $(currentElement).css('opacity');
if (currOp == 1) $(currentElement).css('opacity', 0.5);
if (currOp == 0.5) $(currentElement).css('opacity', 1);
});
}
Run Code Online (Sandbox Code Playgroud)
使用三元运算符:
$(currentElement).css('opacity', currOp == 1 ? 0.5 : 1);
Run Code Online (Sandbox Code Playgroud)
作为一个方面说明:我习惯使用===过==,以避免意外的类型强制意外的错误.要在这里使用它,我会currOp通过+以下方式解析数字:
$(currentElement).css('opacity', +currOp === 1 ? 0.5 : 1);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看此处.