簡體   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