简体   繁体   中英

writing if/else statement as ternary operator

How would I write this using a 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'); } 

I have tried

 !$('#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'); 

Simplify.

CSS:

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

No JavaScript required.

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

You can do something like this

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


More simplified as @Rayon suggested

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

Try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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