简体   繁体   English

确定奇数和偶数

[英]Determining odd and even numbers

Can someone tell me what I am doing wrong here? 有人可以告诉我我在做什么错吗? What I am trying to do is looping through the list and assign a background colour for odd and even numbers. 我想做的是遍历列表,并为奇数和偶数分配背景色。

Thanks in advance. 提前致谢。

 var box = document.querySelectorAll('.links-wrapper li'); for(var i = 0; i < box.length; i++){ if(box[i] % 2 === 0){ box[i].style.backgroundColor = 'red'; } else { box[i].style.backgroundColor = 'blue'; } } 

Change box[i] to i box[i]更改为i

for(var i = 0; i < box.length; i++){
    if(i % 2 === 0){
        box[i].style.backgroundColor = 'red';
    } else {
        box[i].style.backgroundColor = 'blue';
    }
}

Else you can use css psuedo selector 否则您可以使用CSS psuedo选择器

 .links-wrapper li:nth-child(even) { color: red } .links-wrapper li:nth-child(odd) { color: green } 
 <ul class="links-wrapper"> <li> 1</li> <li> 2</li> <li> 3</li> <li> 4</li> <li> 5</li> </ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM