2016-04-18 13 views
0

下記のプログラムのJavaScript x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";"のこのコード行は何ですか?とは何ですか? JavaScriptでどのように動作しますか?

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

答えて

3

ternary operatorです。

状態?ただし、expr1:同じですexpr2の

として:あなたのケースでそう

if (condition) expr1; 
else expr2; 

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

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

に相当します

関連する問題