2016-06-12 10 views
0

私は、次のJSコードがあります。変更色

<div> item1 </div> 
<div> item2 </div> 
<div> item3 </div> 

var x = document.querySelectorAll('div'); 

for(var i = 0; i < x.length; i++){ 
    x[i].addEventListener("click", function(){ 
    for(var i = 0; i < x.length; i++){ 
     if(x[i].style.color === ""){ 
     x[i].style.color = "red" 
     } else { 
     x[i].style.color = "" 
     } 
    } 
}); 
} 

を私は色はそれらのすべてに変更し得る代わりに、クリック上の色に各項目を変更したいと思います。クリックした要素の色のみを変更するにはどうすればよいですか?

答えて

1

ハンドラ内の<div>をすべてループしています。簡単な方法は、本である:この場合

for(var i = 0; i < x.length; i++) { 
    if (x[i] !== this) { 
    x[i].style.color = ""; 
    } 
} 
if (this.style.color === "red") { 
    this.style.color = ""; 
} else { 
    this.style.color = "red" 
} 

thisがクリックされた要素を指します。

+0

三項演算子を使うことができます: 'this.style.color = this.style.color ===" "? "red": "" ' – Tushar

+0

@ Tusharこれはあまり明確ではなく、特に新しいコーダーにとっては明らかです。 –

+0

ありがとうございます。でも、1つの要素だけを赤色にしたいのですが? – Alex

0

すべてのdivをループしてリスナーを追加するのではなく、1つのリスナーのみをウィンドウに追加し、divの場合はその色を変更します。

window.addEventListener('click', function(event) { 
    const target = event.target; // what you clicked on 
    if(target.tagName !== 'DIV') { 
     return; // not a <div>, stop the function 
    } 

    const color = target.style.color; 
    target.style.color = color? '' : 'red'; // color is set then clear it, otherwise set to 'red' 
}); 

または:

const divs = document.querySelectorAll('div'); 
Array.from(divs).forEach(div => { 
    div.addEventListener('click', changeColor); 
}); 

function changeColor() { 
    let color = this.style.color; 
    this.style.color = color? '' : 'red'; 
} 

また、あなたは<script> /* JS here */ </script>タグ内のJavaScriptコードをラップする必要があります。