我有一些段落。首先,其中一个应为红色,单击后应变为黑色,单击后应变为红色。我需要在单击每个段落时将其更改为红色,并在单击另一个段落时将其删除。我应该用javascript
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
p[0].classList.remove("active");
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
this.classList.add("active");
}
}
.active{
color: red;
}
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
答案 0 :(得分:1)
您的代码很好,只是有一些逻辑问题:)
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
for( var i = 0; i < p.length; i++ ){
p[i].classList.remove("active");
}
this.classList.add("active");
}
}
.active{
color: red;
}
<p class="active">Text First</p>
<p>Text Second</p>
<p>Text Third</p>
答案 1 :(得分:0)
var p = document.querySelectorAll("p");
p.forEach(para => para.addEventListener("click", makeRed));
p[0].classList.add("active");
function makeRed(){
p.forEach(para => para.classList.remove("active"));
this.classList.add("active");
}
.active{
color: red;
}
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
答案 2 :(得分:0)
尝试以下解决方案,
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
var elems = document.querySelectorAll(".active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
this.classList.add("active");
}
}
.active{
color: red;
}
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
答案 3 :(得分:0)
只需使用document.querySelectorAll
即可获取所有元素,并通过删除active
来重置其类,然后只需将类添加到当前元素即可。
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
[...document.querySelectorAll('p')]
.map(elem => elem.classList.remove("active"));
this.classList.add("active");
}
.active{
color: red;
}
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>