window.onload没有使用ajax loadXMLDoc调用

时间:2014-03-03 15:27:10

标签: javascript ajax html5

我使用JavaScript和AJAX的XMLHttpRequest来加载来自不同* .html的内容,以便从我的初始首页index.html前进到其他html页面。

要添加一些动态行为(尚未添加),我希望通过window.onload=setSelected();自动调用JavaScript函数setSelected()(请参阅下面我如何准确地执行此操作)。

当我从我的首页index.html加载我的第一个html页面introduction.html的内容时,这非常有效。要检查是否调用了setSelected(),我将一条警告消息和一个日志打印输出到控制台。

在index.html中:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="css/base.css" rel="stylesheet" type="text/css"/>
<script src="./js/my_js_lib.js"></script>
</head>

<body>
<div id="bigbackground" class="clearfix">
    <div id="smallbackground" class="clearfix">
        <iframe src="source/introduction.html"></iframe>
    </div>
</div>
</body>
</html>

在introduction.html中:

<head>
<link href="../css/base.css" rel="stylesheet" type="text/css" />
<script src="../js/my_js_lib.js"></script>
<script>
    window.onload=setSelected();
</script>
</head>

<article id='id_intro' onload="setSelected()">
<div class='clearfix'>
    <button value="Next" onclick="loadXMLDoc('instructions.html',
    'id_intro')" class="button_blue">Next</button>
</div>
</article>

在my_js_lib.js中:

function loadXMLDoc(url, id)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {   // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {   // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {                  
        document.getElementById(id).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

function setSelected()
{
    alert('I am setSelected');
    console.log('I am setSelected');
}

但是,在第二个加载的html内容页面instructions.html上使用相同的语法不会通过window.onload再次调用setSelected()。 我没有在控制台收到警报消息或日志打印。

在instructions.html中:

<head>
<script src="../js/my_js_lib.js"></script>
<script>
    window.onload=setSelected();
</script>
</head>

<article id='id_instru' onload="setSelected()">
<div class='clearfix'>

<button value="Intro" onclick="loadXMLDoc('introduction.html', 'id_instru')" class="button_blue">Introduction</button>
<button value="Next"  onclick="loadXMLDoc('speakers_inauguration.html', 'id_instru')" class="button_blue">Next</button>
</div>
</article>

此外,当回到introduction.html时(通过点击第一个带有值=“简介”的按钮),再次出现警报消息和控制台上的日志打印。

我想象有两种可能的错误来源:

a)当初始首页index.html被加载时,window.onload=setSelected();只在html标题处设置一次,但是当我通过AJAX加载更多内容时,它可能不会被添加到html部分,对吧?

b)当我通过AJAX加载它时,不会触发HTML5元素的onload事件处理程序。

最佳,

0 个答案:

没有答案
相关问题