简体   繁体   中英

document.getElementById innerHTML not displaying

This should be a pretty easy thing to do, but it's not returning anything. The function love() should kick off, getting a simple number prompt, and spitting out a list of a few items that uses that starting number. the alert box correctly displays what I expect, but I want it to display on the screen. (this is but a small section of what I'm after, but it's the kernel of it). No text is displaying in the IE, FF, or Chrome...

<script type="text/javascript">
        function love()
        {
            var ncxElement="";
            var idNumber = prompt("Enter beginning number","");
            var myText=document.getElementById("here");
            for (var i=1;i<5;i++)
            {
                ncxElement+=("<navPoint class=\"other\" id=\"page_"+idNumber+"\">\n");
                idNumber++;
            }
                alert(ncxElement);
                myText.innerHTML=ncxElement;
        }
    </script>
    </head>
    <body onload="love()">
    <p id="here">Begin!</p>
    </body>

If you want to display HTML on your page (without it being parsed), use .textContent instead of .innerHTML and wrap it in a <pre> (to preserve the line breaks).

Demo: jsFiddle

Change:

myText.innerHTML=ncxElement;

To:

myText.textContent=ncxElement;

Change:

<p id="here">Begin!</p>

To:

<pre id="here">Begin!</pre>

navPoints are not valid html elements, so the browser doesn't know what to do with them. They are being added to the DOM, just not displayed unless you add styling to do so.

If you replace them with paragraph tags, it works fine. See the example here .

<script type="text/javascript">
    function love()
    {
        var ncxElement="";
        var idNumber = prompt("Enter beginning number","");
        var myText=document.getElementById("here");
        for (var i=1;i<5;i++)
        {
ncxElement+=("<p class=\"other\" id=\"page_"+idNumber+"\">"+idNumber+ "</p>");
            idNumber++;
        }
            alert(ncxElement);
            myText.innerHTML=ncxElement;
    }
</script>
</head>
<body onload="love()">
<p id="here">Begin!</p>
</body>

Your function just wraps elements inside another. There is no text inside or outside these elements to dipslay. Try inserting some random text before closing tags to see the result. Btw, the elements are successfully placed in the p tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM