关于javascript三目

时间:2023-03-09 23:46:38
关于javascript三目

三目运算符能使我们的代码更为简洁,因而包括小编的我也很是青睐它,不过有时候我们给予它更多的希望,小编处于学习阶段,先从笔记开始:

 (3>1)?console.log(1):console.log(2);//

 //expression?expression1:expression2

3>1为true吗?为true的是就执行expression1,否则就执行expression2;

三目嵌套:

 (5>4)?alert(1):((2>1)?alert(2):((4>5)?alert(0):alert(9)));

三目嵌套。表达式1,5>4吗?大于就alert(1),否则就执行表达式2 ,2>1吗?大于就alert(2),否则就执行表达式3,4>5吗?大于就alert(0),否则就alert(9);

来个三目小demo:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三目运算符的运用</title>
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.js"></script>
</head>
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
.red:hover{
background-color: orange;
}
.green:hover{
background-color: cyan;
}
</style>
<body>
<button class="close">关闭</button>
<button class="open">开启</button>
</body>
<script>
$('button').click(function(){
($(this).html()=='关闭')?$(this).html('开启').addClass('green').removeClass('red'):$(this).html('关闭').addClass('red').removeClass('green');
})
</script>
</html>

有时候我们有这样的需求,点击一个按钮,给按钮加一个类,同时删除一个类,同时还要在这个元素上变化很多,为了逻辑清晰,最好还是用if()else()

三目强化:多个值的改变 json方式 必须先声明 否则会报undfined

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三目运算符的运用</title>
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.js"></script>
</head>
<style>
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
<body>
<button class="close">关闭</button>
<span id="box">这是一段小飞写的文字...</span>
</body>
<script>
$('button').click(function(){
var obj={status:'',color:'',size:''};
($(this).html()=='关闭')?obj={font:'开启',color:'green',size:'20px'}:obj={font:'关闭',color:'red',size:'12px'};
$('#box').css({
color:obj.color,
fontSize:obj.size
});
$(this).html(obj.font); })
</script>
</html>

说下这个需求,点击按钮切换span标签里的内容的字体大小和字体颜色,同时切换按钮里的内容。

三目双重判断:个人喜好这么叫


 $(window).scroll(function(event){
$('#box')[$(window).scrollTop()>300?"fadeIn":"fadeOut"]($(window).scrollTop()>300?300:500);
console.log($(window).scrollTop());
});