2016-04-18 15 views
0

Was ist diese Codezeile in JavaScript x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";" in dem unten geschriebenen Programm?Was ist das? in JavaScript und wie funktioniert es?

<!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> 

Antwort

3

Es ist die ternary operator.

Zustand? expr1: expr2

Welche ist die gleiche wie:

if (condition) expr1; 
else expr2; 

So in Ihrem Fall:

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

entspricht:

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