如何在页面加载时调用 JavaScript 函数?

发布于 2024-09-25 22:28:34 字数 342 浏览 1 评论 0原文

后调用 JavaScript 函数,您需要向包含一些 JavaScript 的正文添加一个 onload 属性(通常只调用一个函数)。

<body onload="foo()">

传统上,要在页面加载 运行一些 JavaScript 代码,用来自服务器的数据动态填充页面的某些部分。我无法使用 onload 属性,因为我使用的是 JSP 片段,该片段没有可以添加属性的 body 元素。

还有其他方法可以在加载时调用 JavaScript 函数吗?我不想使用 jQuery,因为我对它不是很熟悉。

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)

<body onload="foo()">

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

不必在意 2024-10-02 22:28:34

如果您希望 onload 方法接受参数,您可以执行类似的操作:

window.onload = function() {
  yourFunction(param1, param2);
};

这将 onload 绑定到一个匿名函数,该函数在调用时将使用您提供的任何参数运行您想要的函数。当然,您可以从匿名函数内部运行多个函数。

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

非要怀念 2024-10-02 22:28:34

另一种方法是使用事件侦听器,以下是使用它们的方法:

document.addEventListener("DOMContentLoaded", function() {
  your_function(...);
});

说明:

DOMContentLoaded 这意味着当文档的 DOM 对象完全加载并被 JavaScript 看到时。也可以是“click”、“focus”...

function() 匿名函数,当事件发生时将被调用。

Another way to do this is by using event listeners, here's how you use them:

document.addEventListener("DOMContentLoaded", function() {
  your_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

妖妓 2024-10-02 22:28:34

您原来的问题不清楚,假设凯文的编辑/解释是正确的,那么第一个选项不适用

典型的选项是使用onload事件:

<body onload="javascript:SomeFunction()">
....

您也可以将您的JavaScript 位于正文的最后;在文档完成之前它不会开始执行。

<body>
  ...
  <script type="text/javascript">
    SomeFunction();
  </script>
</body>

另一种选择是使用本质上执行此操作的 JS 框架:

// jQuery
$(document).ready( function () {
  SomeFunction();
});

Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply

The typical options is using the onload event:

<body onload="javascript:SomeFunction()">
....

You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.

<body>
  ...
  <script type="text/javascript">
    SomeFunction();
  </script>
</body>

Another option is to use a JS framework which intrinsically does this:

// jQuery
$(document).ready( function () {
  SomeFunction();
});
江心雾 2024-10-02 22:28:34
function yourfunction() { /* do stuff on page load */ }

window.onload = yourfunction;

如果您愿意,也可以使用 jQuery:

$(function(){
   yourfunction();
});

如果您想在页面加载时调用多个函数,请查看这篇文章以获取更多信息:

function yourfunction() { /* do stuff on page load */ }

window.onload = yourfunction;

Or with jQuery if you want:

$(function(){
   yourfunction();
});

If you want to call more than one function on page load, take a look at this article for more information:

青丝拂面 2024-10-02 22:28:34
<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>
    
    </body>
</html>

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>
    
    </body>
</html>

遮了一弯 2024-10-02 22:28:34

您必须调用要在加载时调用的函数(即加载文档/页面)。
例如,您要在文档或页面加载时加载的函数称为“yourFunction”。这可以通过调用文档加载事件的函数来完成。请参阅下面的代码了解更多详细信息。

尝试下面的代码:

<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        yourFunction();
    });
    function yourFunction(){
      //some code
    }
</script>

You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.

Try the code below:

<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        yourFunction();
    });
    function yourFunction(){
      //some code
    }
</script>
你是我的挚爱i 2024-10-02 22:28:34

这是技巧(在任何地方都适用):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

here's the trick (works everywhere):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
£噩梦荏苒 2024-10-02 22:28:34

这是一个使用 es6 且没有 jquery 的示例:

window.onload = () => {
  foo()
}

请参阅 mdn 文档: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

here's an example with es6 and no jquery:

window.onload = () => {
  foo()
}

see the mdn docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

温柔女人霸气范 2024-10-02 22:28:34

要检测插入到 DOM 中的加载的 html(从服务器),请使用 MutationObserver 或检测 loadContent 函数中数据可供使用的时刻

let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
  if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });


// TEST: simulate element loading
let tmp=1;
function loadContent(name) {  
  setTimeout(()=>{
    console.log(`Element ${name} loaded`)
    content.innerHTML += `<div>My name is ${name}</div>`; 
  },1500*tmp++)
}; 

loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use

let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
  if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });


// TEST: simulate element loading
let tmp=1;
function loadContent(name) {  
  setTimeout(()=>{
    console.log(`Element ${name} loaded`)
    content.innerHTML += `<div>My name is ${name}</div>`; 
  },1500*tmp++)
}; 

loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文