javascript - 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>
解决方案
在 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();
正在执行功能meow
和rawr
。您可能希望传递对这些函数的引用:
document.getElementById("thisbutton").onclick(meow);
document.onload = rawr;
推荐阅读
- javascript - 按id删除数组中的多个对象
- scala - from_json 未在 spark 结构化流中将 json 转换为 DF
- amazon-web-services - AWS Lambda 和 Amazon S3 资源是否可以存在于同一个 CloudFormation 模板中?
- java - 尝试从 gitlab 检索配置信息时获取“无效的 cookie 标头:“Set-Cookie:experimentation_subject_id ...”
- ubuntu - Visual Studio Code - 在 linux 中禁用更新检查
- loops - 到第 28 天结束时,会有多少只绿蝇?请检查程序是否是正确的解决方案
- javascript - 无法使用获取的数据根据输入值进行搜索。收到过滤器错误
- pandas - 如何在 dask 中编写 unstack 和 reindex?
- ios - QML 更改 iPhone 凹槽和底部区域的颜色
- sqlite - Xamarin.Forms 和 EntityFrameworkCore 3.x 如何正确创建数据库并应用迁移?