我想使用vanilla Javascript来更改标签的颜色,只要使用“this”关键字点击该标签。该元素以红色开始。如果在红色时单击,则会变为绿色。如果在绿色时点击它,则会变为蓝色。如果在蓝色时单击,则会变为红色。在Javascript中使用“this”
看起来很简单,根据我的资源我的代码应该工作,但事实并非如此。我在这里错过了什么?
这里是我的javascript:
<script type="text/javascript">
function changeColor(obj) {
if (obj.style.backgroundColor=="#ff0000") {
obj.style.backgroundColor="#00ff00";
} else if (obj.style.backgroundColor=="#00ff00") {
obj.style.backgroundColor="#0000ff";
} else {
obj.style.backgroundColor="#ff0000";
}
}
</script>
这是我的HTML:
<a style="background-color: #ff0000;" onclick="changeColor(this)" href="#">Click me</a>
我觉得这个问题是有关的人谁刚开始学习如何使用 “this” 关键字。
谢谢!
@CBroe *不*这个问题的重复。完全一样。 –
[了解如何调试JavaScript](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820) –