在html元素中显示数据

时间:2022-12-08 11:33:31

I have a small doubt. I want to display some data on my page using innerHTML property. But when I try to do so, the data wont render on my page. But if I use document.writeln(), the data is rendering on the page. I want to display the data in the span element with id="verify". How can I do that? Here is my code:

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

<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 个解决方案

#1


1  

In addition to Cheery's answer, you should always put your javascript at the end of your body, unless you need it to display something on the page before it loads. This will give you better performances and will probably eliminate most of these small mistakes like trying to fetch an element before the page loads.

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

#1


1  

In addition to Cheery's answer, you should always put your javascript at the end of your body, unless you need it to display something on the page before it loads. This will give you better performances and will probably eliminate most of these small mistakes like trying to fetch an element before the page loads.

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