在页面加载时调用 JavaScript 函数
加载网页时可以调用的函数。这个约定取决于浏览器对象 window
及其属性 onload
。了解你的函数是否被调用的基本方法是检查控制台面板。
对于演示示例,我们将考虑一个 HTML 结构,我们希望在其中可视化我们的输出。每次我们重新加载网页时,控制台面板都会响应由 window.onload
属性指示的给定语句。
以变量为参数的 JavaScript 函数
在这里,我们将使用一个将变量作为参数的函数。此外,在 jsbin 中试验的编码驱动是为了更好地理解。无论哪种方式,你都可以使用你的浏览器和首选编辑器。
代码片段:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
</head>
<body onload = func()>
<p id="output"></p>
<script>
var x = 40;
var y = 2;
function func(x, y){
return x+y;
}
window.onload = function(){
console.log(func(x,y));
}
document.getElementById('output').innerHTML = func(x,y);
</script>
</body>
</html>
输出:
在这种情况下,脚本部分被添加到 HTML 正文中,如你所见,在网页的每次加载时,控制台都有一个值,说明整个代码正在运行。
此外,window.onload
的基本用例是确保每次都成功加载页面。它很可能用作确保 HTML 中无错误代码块的参数。因此,你可以根据自己的方便在任何地方使用它。
加载时以函数为参数的 JavaScript 调用函数
以下示例将以不同方式解释 window.onload
属性的功能。我们将使用一个 HTML 代码部分和一个单独的 JavaScript 代码部分。我们函数的参数是其他一些函数。
代码片段:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<style>
p{
background: white;
}
</style>
</head>
<body onload = func()>
<p id="output"></p>
</body>
</html>
function f1() {
return '4';
}
function f2() {
return '2';
}
function func(f1, f2) {
return f1() + f2();
}
window.onload =
function() {
console.log(func(f1, f2));
}
document.getElementById('output')
.innerHTML = func(f1, f2);
输出:
从输出场景来看,每当按下 Run with JS
时,它都会提供类似加载网页的体验。代码没有错误,这是我们可以通过在每次页面加载时调用函数得出的可推断语句。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。