我是Javascript的新手,所以请随意指出我做错的事情。每次点击一个按钮,我都会尝试更改div的颜色。到目前为止,这是我的代码:
function setBgColour(){
if (.backgroundColor == '#ff0000'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
} else if (.backgroundColor == '#ffff00'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00'
} else if (.backgroundColor == '#00ff00'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000'
}
}
window.onload = function(){
document.getElementById('next').addEventListener('click', setBgColour);
};
答案 0 :(得分:1)
问题在于您的条件陈述。你在做什么:
if (.backgroundColor == '#ff0000')
您要查看的元素是什么,以获取backgroundColor
属性?
您应该执行以下操作:
window.onload = function() {
var current = '#ff0000';
function setBgColour() {
var light = document.getElementsByClassName("light")[0];
if (current == '#ff0000') {
current = '#ffff00';
} else if (current == '#ffff00') {
current = '#00ff00';
} else if (current == '#00ff00') {
current = '#ff0000';
}
light.style.backgroundColor = current;
}
document.getElementById('next').addEventListener('click', setBgColour);
setBgColour();
};

.light {
width: 100px;
height: 100px;
}

<div class="light"></div>
<button id="next">Next</button>
&#13;