【发布时间】:2016-11-17 21:03:22
【问题描述】:
以下 html 网页包含一个按钮。如果单击页面中包含的按钮,按钮的颜色应该变为红色(根据 js 代码)。但是,它不起作用,我不明白为什么它不起作用。 事实上,我周围没有人明白为什么它不起作用。如果有人知道发生了什么,请帮助我!
<!DOCTYPE html>
<html>
<body>
<h1>Please click the button below, it will turn red.</h1>
<button type="button" onclick="myFunction(this)">Set background color</button>
<script>
function myFunction(element) {
element.style.backgroundColor = "red";
}
</script>
</body>
</html>
更新:上面的代码有效,对此感到抱歉。在将原始代码发布到此处之前,我已经简化了原始代码。我的目标是将代码减少到基本部分。 您可以在下面找到原始代码。如果我按两次按钮,它应该变成绿色。但是,它保持红色。我不明白为什么。
<!DOCTYPE html>
<html>
<body>
<h1>Please click the button below, it will turn red.</h1>
<button type="button" onclick="setColor(this)">Set background color</button>
<script>
lastField = null;
function setColor(element) {
if (element === lastField) {
element.style.backgroundColor = "green";
}
element.style.backgroundColor = "red";
lastField = element;
}
</script>
</body>
</html>
【问题讨论】:
-
你用的是什么浏览器?
-
像魅力一样工作
-
检查浏览器是否有任何 JavaScript 错误。
-
您的
if语句将背景设置为绿色。无论if是否为真,下一行代码都将其设置回红色。
标签: javascript html this