繁体   English   中英

将if / else语句编写为三元运算符

[英]writing if/else statement as ternary operator

我将如何使用三元运算符编写此代码?

 if (!$('#privacy_check').is(':checked')) { $('#privacy_check').css('outline-color', 'red'); $('#privacy_check').css('outline-style', 'solid'); $('#privacy_check').css('outline-width', 'thin'); } else { $('#privacy_check').css('outline-color', 'none'); $('#privacy_check').css('outline-style', 'none'); $('#privacy_check').css('outline-width', '0'); } 

我努力了

 !$('#privacy_check').is(':checked') ? $('#privacy_check').css('outline-color', 'red'); $('#privacy_check').css('outline-style', 'solid');$('#privacy_check').css('outline-width', 'thin') : $('#privacy_check').css('outline-color', 'none');$('#privacy_check').css('outline-style', 'none');$('#privacy_check').css('outline-width', '0'); 

简化。

CSS:

#privacy_check {
    outline: thin solid red;
}
#privacy_check:checked {
    outline: none;
}

无需JavaScript。

var $elem = $('#privacy_check');
$elem.css($elem.is(':checked') ?
    { outlineColor: 'none', outlineStyle: 'none', outlineWidth: 0 } :
    { outlineColor: 'red', outlineStyle: 'solid', outlineWidth: 'thin' })

你可以做这样的事情

 $('#privacy_check').change(function() { $(this).css({ 'outline-color': this.checked ? 'none' : 'red', 'outline-style': this.checked ? 'none' : 'solid', 'outline-width': this.checked ? '0' : 'thin' }); }).change() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="privacy_check" /> 


@Rayon建议更简化

 $('#privacy_check').change(function() { $(this).css("outline", this.checked ? 'none' : "thin solid red") }).change() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="privacy_check" /> 

尝试这个:

var $elem = $('#privacy_check');

if($elem.is(":checked")){
    $elem.css("outline", "thin solid red");
}
else{
   $elem.css("outline", "none");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM