2014-11-14 665 views
7

我希望我的Button每次點擊它時都會改變顏色。但它只會在第一次點擊時改變顏色。更改按鈕顏色onClick

我認爲問題出在setColor函數。每次我點擊Button時,count都被設置爲1.因此,即使我將其設置爲0,它也會在下次單擊時重置爲1。我該如何解決? javascript/html中有全局變量,這很容易解決嗎?

<!DOCTYPE html> 
<html> 
<head> 

<script> 
function setColor(btn, color){ 
    var count=1; 
    var property = document.getElementById(btn); 
    if (count == 0){ 
     property.style.backgroundColor = "#FFFFFF" 
     count=1;   
    } 
    else{ 
     property.style.backgroundColor = "#7FFF00" 
     count=0; 
    } 

} 
</script> 
</head> 

<body> 

<input type="button" id="button" value = "button" style= "color:white" onclick="setColor('button', '#101010')";/> 

</body> 
</html> 
+0

是,移動變種Ç ount = 1在函數之前,它將是全局的。 – Bushrod 2014-11-14 19:29:39

回答

8

確實有在JavaScript中的全局變量。你可以瞭解更多關於scopes,這在這種情況下很有幫助。

您的代碼看起來是這樣的:

<script> 
    var count = 1; 
    function setColor(btn, color) { 
     var property = document.getElementById(btn); 
     if (count == 0) { 
      property.style.backgroundColor = "#FFFFFF" 
      count = 1;   
     } 
     else { 
      property.style.backgroundColor = "#7FFF00" 
      count = 0; 
     } 
    } 
</script> 

希望這有助於。

0

每次setColor被擊中,要設置計數= 1.您需要定義count外設功能的範圍。例如:

var count=1; 
function setColor(btn, color){ 
    var property = document.getElementById(btn); 
    if (count == 0){ 
     property.style.backgroundColor = "#FFFFFF" 
     count=1;   
    } 
    else{ 
     property.style.backgroundColor = "#7FFF00" 
     count=0; 
    } 

} 
5

1.

function setColor(e) { 
    var target = e.target, 
     count = +target.dataset.count; 

    target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF'; 
    target.dataset.count = count === 1 ? 0 : 1; 
    /* 

    () : ? - this is conditional (ternary) operator - equals 

    if (count === 1) { 
     target.style.backgroundColor = "#7FFF00"; 
     target.dataset.count = 0; 
    } else { 
     target.style.backgroundColor = "#FFFFFF"; 
     target.dataset.count = 1; 
    } 
    target.dataset - return all "data attributes" for current element, 
    in the form of object, 
    and you don't need use global variable in order to save the state 0 or 1 
    */ 
} 


<input 
    type="button" 
    id="button" 
    value="button" 
    style="color:white" 
    onclick="setColor(event)"; 
    data-count="1" 
/> 

2.

function setColor(e) { 
    var target = e.target, 
     status = e.target.classList.contains('active'); 

    e.target.classList.add(status ? 'inactive' : 'active'); 
    e.target.classList.remove(status ? 'active' : 'inactive'); 
} 

.active { 
    background-color: #7FFF00; 
} 

.inactive { 
    background-color: #FFFFFF; 
} 

<input 
    type="button" 
    id="button" 
    value="button" 
    style="color:white" 
    onclick="setColor(event)" 
/> 

([conditional (ternary) operator])

Example-1

Example-2