如何在JS中页面加载时调用函数? [英] How to call function on page load in JS?

查看:609
本文介绍了如何在JS中页面加载时调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的js函数

I have a js function which looks like this

 function showProducts(){
    document.getElementById("shopList").innerHTML = "<ul><li>Test Text</li></ul>";
 }

此功能必须显示我的产品阵列.我在html页面中用id="shopList"做了一个div

It's a function that has to show an array of my products. I've made an div with id="shopList" in my html page

        <div id="shopList">
        </div>

但是如何调用该函数向我显示div中的文本?当我将其用作主体标签时,它可以工作,但不允许我在html中编写任何js代码或使用onload或onclick.我试图用听众来做将近4个小时,但我仍然没有找到解决方案.有人可以帮我吗?

But how can I call the function to show me the text in the div? It works when I use this as my body tag but I'm not allowed to write any js code in my html or to use onload or onclick. I'm trying to do it with listeners for almost 4 hours and I still did not find a solution. Could someone help me?

     <body onload="showProducts()">

推荐答案

使用纯JavaScript:

Using pure javascript:

window.onload = function(){

};

(或

function doLoad() {
    //Do stuff on load
}

window.onload = doLoad;

使用Jquery

$(document).ready(function(){   

}); 

这篇关于如何在JS中页面加载时调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆