获取document.body错误。救命!

时间:2010-09-04 13:01:37

标签: javascript html notifications

我有以下JavaScript代码:

function createNotification(title, body, canDismiss, callback)
{
    //create the container
    var nContainer = document.createElement("div");
    nContainer.setAttribute("id", "note"+title);
    nContainer.setAttribute("class","nContainer");
    nContainer.className = "nContainer";

    //create the title
    var nTitle = document.createElement("div");
    nTitle.setAttribute("class", "nTitle");
    nTitle.className = "nTitle";
    nTitle.innerHTML = title;

    //if canDismiss is true then add controls
    if (canDismiss)
    {
        var nDismiss = document.createElement("div");
        nDismiss.setAttribute("class", "nDismiss");
        nDismiss.className = "nDismiss";
        nDismiss.innerHTML = "[close]";
        nDismiss.onclick = function(){destroyNotification(title);callback();};
        nTitle.appendChild(nDismiss);

    }

    //append the title to the container
    nContainer.appendChild(nTitle);

    //create the body and append to container
    var nBody = document.createElement("div");
    nBody.setAttribute("class", "nBody");
    nBody.className = "nBody";
    nBody.innerHTML = body;
    nContainer.appendChild(nBody);

    document.body.appendChild(nContainer);

    //fade background
    fadeIt(title);
}

function destroyNotification(title)
{
    //get the specified notification
    var note = document.getElementById("note"+title);

    //remove the notification
    document.body.removeChild(note);

    //unfade the background
    unfadeIt(title)
}

function fadeIt(title)
{
    //create a partially opaque div and append it to the document
    var Fade = document.createElement("div");
    Fade.setAttribute("id", "fade"+title);
    Fade.setAttribute("class","fade");
    Fade.className = "fade";
    document.body.appendChild(Fade);
}

function unfadeIt(title)
{
    //get the specified fade element
    var Fade = document.getElementById("fade"+title);

    //remove the specified fade element
    document.body.removeChild(Fade);
}

我收到了document.body错误。有人可以帮忙吗?

这是html:

<html>
<head>
<title></title>
<script langauge="javascript" type="text/javascript" src="notification.js"> </script>
<link rel="stylesheet" type="text/css" href="notification.css" /> 
<script language="javascript" type="text/javascript">

createNotification("The Title", "Some sort of message for our body", true, function(){alert("A Callback");});


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

我从firebug得到的错误是:

  

document.body为null

     

[打破此错误] document.body.appendChild(nContainer);

3 个答案:

答案 0 :(得分:3)

在页面加载之前,您正在执行函数createNotification。调用它时,body元素甚至不存在。

调用页面底部的函数或添加加载事件[link]

答案 1 :(得分:0)

文档对象有属性“body”。

document.getElementsByTagName("body")[0].removeChild(note);

答案 2 :(得分:0)

您何时执行代码?我的意思是,什么方法被调用:文档加载后或之前的某个地方?我也无法理解createNotification中的一行代码:

function nBody.innerHTML = body; 

您可以在body标签内调用此方法而不是head标签吗?或者您可以使用window.onload事件来调用此函数吗?