【问题标题】:javascript function doesn't get called [closed]javascript函数没有被调用[关闭]
【发布时间】: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


【解决方案1】:

第一次点击,lastField为空,所以背景设置为红色,lastField设置为元素。

第二次点击,lastField是元素,所以背景设置为绿色……然后背景立即设置为红色,lastField设置为元素。

第三次及后续时间与第二次相同。

你需要一个else

【讨论】:

    猜你喜欢
    • 2011-12-30
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多