首页 > 解决方案 > Javascript 函数即使没有被调用也会被执行

问题描述

嗨所以我对javascript相当陌生,现在我正在尝试定义函数和隐藏/显示特定元素。

在我制作的这个简单程序中,我试图在函数仍在执行时显示加载屏幕。问题是,即使不单击按钮,onlick 事件处理程序内部的函数也会执行

<body>
<button id="thisbutton" type="button">clickme</button>
<div>
    <p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>
</div>
<div id="loadss" class="LockOn"></div>

<script>

    document.getElementById("thisbutton").onclick(meow());
    document.onload = rawr();
        function rawr() {
        document.getElementById("loadss").style.visibility = "hidden";
        document.getElementById("loadss").style.display = "none";
        }

        function meow() {
            document.getElementById("loadss").style.visibility = "visible";
            document.getElementById("loadss").style.display = "block";
            time();
            document.getElementById("loadss").style.visibility = "hidden";
            document.getElementById("loadss").style.display = "none";
        };
        function time() {
            var timeleft = 10;
            var downloadTimer = setInterval(function () {
                timeleft--;
                document.getElementById("countdowntimer").textContent = timeleft;
                if (timeleft <= 0)
                    clearInterval(downloadTimer);
            }, 1000);
        }
</script>

标签: javascripthtml

解决方案


在 Javascript 中,函数是一等公民。这意味着您可以像对待大多数变量一样对待它们:

function test () { console.log('Hi!'); }

var x = test;

您可以通过在对它们的任何引用上使用括号来执行它们:

test(); // will execute function test
x(); // will _also_ execute function test

因此,您的代码:

document.getElementById("thisbutton").onclick(meow());
document.onload = rawr();

正在执行功能meowrawr。您可能希望传递对这些函数的引用:

document.getElementById("thisbutton").onclick(meow);
document.onload = rawr;

推荐阅读