在窗口焦点事件之前,在HTML的body标签中运行onload事件

时间:2016-01-25 14:40:52

标签: javascript

我想在HTML页面中的焦点事件之前调用onload事件。 在我的以下代码中

<!DOCTYPE html>
<html>
<head>
<body onload='onloading()'>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(window).focus(function(){

        callMe();
    });
});

function callMe()
{
    alert('Focus is on current page');
}

function onloading()
{
    alert('Onload function call ');
}
function myFunction() 
{
  document.write("some text");
}
document.getElementById("demo").innerHTML = myFunction(); 
</script>
</head>
<p id="demo"></p>
</body>
</html>

当我执行此代码时,我会弹出一个&#34;专注于当前页面&#34;并在后面&#34;一些文字&#34; 。但我希望按以下顺序获得输出

  1. &#34;一些文字&#34;&#34;在后台
  2. &#34; Onload function call&#34;弹出
  3. &#34;专注于当前页面&#34;弹出 。
  4. 但我没有弹出#34; Onload函数调用&#34; :(。我需要在焦点事件之前在身体中运行onload事件。是否可以做这样的事情?

2 个答案:

答案 0 :(得分:1)

您的HTML无效。您已将head标记放在body内,这是不允许的。

使用以下结构:

<html>
    <head>
        <script></script>
    </head>
    <body>
    </body>
</html>

答案 1 :(得分:1)

试试这个:

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<p id="demo"></p>
<p id="focus">Click here</p>
  
<script type="text/javascript">
function callMe()
{
    $("#focus").html('Focus is on current page');
}

function onloading()
{
    alert('Onload function call ');
}
function myFunction() 
{
 $("#demo").html("some text");
}
$(window).load(function () {
 onloading();
});
$(document).ready(function(){
    $("#demo").html= myFunction(); 
    $(window).focus(function(){
       callMe();
    });
});
</script>

</body>
</html>