2016-12-01 1 views
0

버튼을 클릭하면 텍스트가 녹색으로 바뀌고 텍스트를 다시 클릭하면 텍스트가 파란색으로 변합니다. 텍스트 또는 파란색 인 경우 녹색이라면이 일을 나의 전략은 테스트했다,하지만 난 방법을 알고하지 않았다 : "If 문"을 사용하여 자바 스크립트에서 색상이 지정된 텍스트의 값을 얻습니다.

var topcon = document.getElementsByClassName("topchoice"); 

function show() { 
    if(topcon.style.color = "blue") { 
     for (count=0; count < topcon.length; count++) { 
     topcon[count].style.color = "green"; 
     } 
    } 
    else if(topcon.style.color = "green") { 
     for (count=0; count < topcon.length; count++) { 
      topcon[count].style.color = "blue"; 
     } 
    } 
} 

그러나,이 작동하지 않습니다. show() 함수를 호출하면 같은 색상으로 유지됩니다. 왜 이것이 작동하지 않는지 아는 사람이 있습니까?

왜 내가 루프를 사용했는지 궁금하다면 요소가 배열로 작동하기 때문에 배열이없는 getElementsByClassName을 사용할 수 없기 때문입니다.

+2

같은 오류가 발생하는 코드를 발생합니다'===은' –

+1

는'topcon'는 노드 컬렉션은,이다 'uncaught TypeError : undefined의 'color'속성을 설정할 수 없습니다. ' –

+0

당신은 무엇을하려고합니까? 첫 번째 색상의 색상을 기반으로 모든 요소의 색상을 변경하려고합니까, 아니면 각 요소 색상을 독립적으로 전환해야합니까? –

답변

2

은, 코드

  • 비교
  • topcon에 대한 비교 연산자 == 또는 ===을 사용할 필요가 노드 목록입니다 2 문제가 있습니다. 이것은`=`당신이 원하는 당신이 그것을 할당하는 Uncaught TypeError: Cannot set property 'color' of undefined

var topcon = document.getElementsByClassName("topchoice"); 
 

 
function show() { 
 
    var el; 
 
    for (count = 0; count < topcon.length; count++) { 
 
    el = topcon[count]; 
 
    if (el.style.color == "blue") { 
 
     el.style.color = "green"; 
 
    } else if (el.style.color == "green") { 
 
     el.style.color = "blue"; 
 
    } 
 
    } 
 
}
<div class="topchoice" style="color: green">1</div> 
 
<div class="topchoice" style="color: green">1</div> 
 
<div class="topchoice" style="color: green">1</div> 
 
<div class="topchoice" style="color: green">1</div> 
 

 
<button onclick="show()">Show</button>

+0

과 같은 것을 찾고 계십니까? 제안을 위해, 이것은 도움이된다! – MCGuy

+0

하지만 단 한가지 문제가 있습니다 : CSS 파일에서 텍스트의 스타일을 지정하려고하면 버튼을 클릭 할 때 텍스트가 변경되지 않습니다. 혹시이 문제를 해결하는 방법을 알고 있습니까? – MCGuy

+0

@MCGuy 더 많은 정보를 공유 할 수 있습니까? –

1

대입 연산자 "="보다는 비교 연산자 "==="를 사용해야합니다. 또한 topcon이 항목 배열이 될 것으로 예상하는 것처럼 보이기 때문에 다소 혼란 스럽습니다.이 경우 선택된 항목의 요소와 비교를 변경해야합니다. 는 style 속성을하지 않도록

var topcon = document.getElementsByClassName("topchoice"); 

function show() { 
    var changeColor = "blue"; 
    if(topcon && topcon.length) { 
    if(topcon[0].style.color === "blue") { 
     changeColor = "green"; 
    } else { 
     changeColor = "blue"; 
    } 
    for (count=0; count < topcon.length; count++) { 
     topcon[count].style.color = changeColor; 
    } 
    } 
}; 
관련 문제