2014-11-14 2 views
7

클릭 할 때마다 내 Button 색깔을 변경하고 싶습니다. 하지만 첫 번째 클릭 만 변경됩니다.버튼 색상 변경 onClick

나는이 문제가 setColor 기능에 있다고 생각합니다. Button을 클릭 할 때마다 count은 1로 설정됩니다. 따라서 0으로 설정하더라도 다음 클릭시 1로 재설정됩니다. 이 문제를 어떻게 해결할 수 있습니까? 이것이 쉽게 해결 될 자바 스크립트/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

예, 이동 var에 C ount = 1을 함수 앞에 붙이면 전역 변수가됩니다. – Bushrod

답변

8

실제로 자바 스크립트에는 전역 변수가 있습니다. 이 상황에서 도움이되는 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