在html页面加载时执行一个函数

时间:2013-07-04 15:19:22

标签: javascript html

我正在尝试在页面运行时立即执行javascript函数。我认为这会起作用,但事实并非如此。我究竟做错了什么?谢谢!

    <script language="javascript" type="text/javascript">
    <!-- 
    //Browser Support Code
        window.onload = function runAtLoadTime() {
            getInfo;
        }

        function getInfo() {
            alert("here");
            console.log("here");
        }
   //-->
   </script>

2 个答案:

答案 0 :(得分:4)

您需要使用()才能调用函数。替换

getInfo;

通过

getInfo();

或者考虑到runAtLoadTime除了拨打getInfo之外没有任何逻辑,你可以这样做

// assign getInfo to onload, I'm not calling it here, that's why () are not used
window.onload = getInfo; 

答案 1 :(得分:0)

onload对象的window属性接受您已正确分配的函数。但是在您的功能中,您没有执行函数调用。如果您的事件处理程序包含除调用getInfo函数之外的逻辑,则使用第一个。否则使用第二个。你有两种选择:

// Function call inside your event handler
window.onload = function runAtLoadTime() {
     getInfo();
}

// Assigning the function directly
window.onload = getInfo;