打开一个新的html文件后,getElementById返回null

时间:2014-03-22 05:50:51

标签: javascript html dom

我在点击其他html文件中的图片后通过javascript加载新的html文件。我这样说window.location.href="page2.html"现在,当尝试使用getElementById()访问page2.html上的元素时,它总是返回null。我认为我的DOM是从第一页创建的,所以它返回null,因为我提供的id不在第一页,而是第二页。如何刷新我的DOM以表示我的新页面?

我的第一个HTML页面

<!DOCTYPE html>
<html>

<link rel="stylesheet" type="text/css" href="mystyle.css">
<head>
    <script src="myScript.js"></script>
</head>

<body class="homepage">
    <header>
        <h1> $ Cheap Gamer $ </h1>
        <p> Welcome to the best website in the world to find great deals on cheap games </p>
    </header>

    <ul>
        <h1 id=pcheader> PC Games </h1>
        <li>Crysis</li>
        <p>An intense first person shooter. $9.99</p>
        <img id="1" src="crysis.jpg" onClick="showDetails(id)">

        <li>Battlefield</li>
        <p>A great multi player experience. $5.99</p>
        <img id="2" src="bc2.jpg"  onClick="showDetails(bc2)">
    </ul>
    <ul>
        <h2 id=mobileheader> Mobile Games </h2>
        <li>Angry Birds</li>
        <p> The most popular mobile game of all time! Availabe now for free!</p>
        <img  id="3" src="angry.jpg" alt="Smiley face" height="42" width="42" onClick="showDetails(angry)">

        <li>Angry Pigs</li>
        <p> The long awaited follow up the the classic Angry Birds. Now for free!</p>
        <img   id="4" src="angrybirds.jpg" alt="Smiley face" height="42" width="42" onClick="showDetails(angrybirds)">
    </ul>

    <footer id="footer">
        Contact tylerpfaff@gmail.com for any inquries
    </footer>

</body>

我的第二个HTML页面

<!DOCTYPE html>
<html>

<head>
    <script src="myScript.js"></script>
</head>

<h1 id=headertext></h1>
<img id=boxart height="500" width="500"></img>
</html>

我的脚本文件

function showDetails(imgid){
var imgsrc;
    window.location.href="page2.html"
    alert(imgid);
    switch(imgid)
    {
    case "1":
    alert(document.getElementById("boxart"));
    break;
    case 2:
    imgsrc="BattefieldLarge.jpg"
    break;

    case 3:
    imgsrc="AngryBirdsLarge.jpg"
    break;

    case 4:
    imgsrc="AngryPigsLarge.jpg"
    break;

    }

}

0 个答案:

没有答案