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

时间:2016-05-26 09:50:35

标签: javascript jquery

我如何使用三元运算符编写它?

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');

4 个答案:

答案 0 :(得分:4)

简化。

CSS:

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

无需JavaScript。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你可以做这样的事情

$('#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" />

答案 3 :(得分:0)

试试这个:

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

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