关于javascript三目

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

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

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

三目嵌套:

1 (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:

 1 <!DOCTYPE html>
 2 <html >
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>三目运算符的运用</title>
 6     <script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.js"></script>
 7 </head>
 8 <style>
 9 .red{
10     background-color: red;
11 }
12 .green{
13     background-color: green;
14 }
15 .red:hover{
16     background-color: orange;
17 }
18 .green:hover{
19     background-color: cyan;
20 }
21 </style>
22 <body>
23     <button class="close">关闭</button>
24     <button class="open">开启</button>
25 </body>
26 <script>
27 $('button').click(function(){
28     ($(this).html()=='关闭')?$(this).html('开启').addClass('green').removeClass('red'):$(this).html('关闭').addClass('red').removeClass('green');
29 })
30 </script>
31 </html>

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

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

 1 <!DOCTYPE html>
 2 <html >
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>三目运算符的运用</title>
 6     <script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.js"></script>
 7 </head>
 8 <style>
 9 .red{
10     background-color: red;
11 }
12 .green{
13     background-color: green;
14 }
15 </style>
16 <body>
17     <button class="close">关闭</button>
18     <span >这是一段小飞写的文字...</span>
19 </body>
20 <script>
21 $('button').click(function(){
22     var obj={status:'',color:'',size:''};
23     ($(this).html()=='关闭')?obj={font:'开启',color:'green',size:'20px'}:obj={font:'关闭',color:'red',size:'12px'};
24     $('#box').css({
25         color:obj.color,
26         fontSize:obj.size
27     });
28     $(this).html(obj.font);
29 
30 })
31 </script>
32 </html>

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

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

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