是什么 ?在JavaScript中它是如何工作的?

时间:2016-04-18 07:58:11

标签: javascript html

下面编写的程序中JavaScript x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";"中的这行代码是什么?

   <!DOCTYPE html>
   <html>
   <body>

   <p>In this example, the setInterval() method executes the setColor()       function once every 300 milliseconds, which will toggle between two background   colors.</p>

   <button onclick="stopColor()">Stop Toggling</button>

   <script>
   var myVar = setInterval(function(){ setColor() }, 300);

   function setColor() {
   var x = document.body;
   x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" :    "yellow";
   }

   function stopColor() {
   clearInterval(myVar);
   }
   </script>

  </body>
  </html>

1 个答案:

答案 0 :(得分:3)

这是ternary operator

  

条件? expr1:expr2

与以下内容相同:

if (condition) expr1;
else expr2;

所以在你的情况下:

x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow"

相当于:

if (x.style.backgroundColor == "yellow")
    x.style.backgroundColor = "pink";
else x.style.backgroundColor = "yellow";