迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在页面加载时调用 JavaScript 函数

作者:迹忆客 最近更新:2024/03/18 浏览次数:

加载网页时可以调用的函数。这个约定取决于浏览器对象 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 时,它都会提供类似加载网页的体验。代码没有错误,这是我们可以通过在每次页面加载时调用函数得出的可推断语句。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便