在html元素中显示数据

时间:2014-10-05 03:12:12

标签: javascript html

我有一点怀疑。我想使用innerHTML属性在我的页面上显示一些数据。但是当我尝试这样做时,数据不会在我的页面上呈现。但是,如果我使用document.writeln(),数据将在页面上呈现。我想在span元素中显示数据,其中id ="验证"。我怎样才能做到这一点?这是我的代码:

<script>
    var now = new Date();
    var hours = now.getHours();
    var name, greeting;
    if(hours < 12)
    {
        greeting = "Good Morning";
    }
    else
    {
        //hours = hours - 12;
        if(hours < 18)
        {
            greeting = "Good Afternoon";
        }
        else
        {
            greeting = "Good Evening";
        }
    }
    if(document.cookie)
    {
        var newCookie = unescape(document.cookie);
        var cookieVals = newCookie.split("=");
        name = cookieVals[1];
    }
    else
    {
        name = window.prompt("Please enter your name","name");
        document.cookie = "name=" + escape(name);
        //document.writeln(greeting + " "+ name + ", welcome to JavaScript programming!" );
        //document.writeln( "<a href = 'javascript:wrongPerson()'> " +"Click here if you are not " + name + "</a>" );
        var a = greeting + " "+ name + ", welcome to JavaScript programming!</h1>" + "<a href = 'javascript:wrongPerson()'> " +"Click here if you are not " + name + "</a>";
        document.getElementById("verify").innerHTML = a;
    }
    function wrongPerson()
    {
        document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT";
        location.reload();
    }
    </script>
    <span id="verify"></span>

1 个答案:

答案 0 :(得分:1)

除了Cheery的回答之外,你应该总是把你的javascript放在身体的尽头,除非你需要它在加载之前在页面上显示一些东西。 这将为您提供更好的性能,并且可能会消除大多数这些小错误,例如在页面加载之前尝试获取元素。