document.getElementById innerHTML not displaying

前端 未结 3 1255
说谎
说谎 2021-01-07 09:36

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

相关标签:
3条回答
  • 2021-01-07 10:08

    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>
    
    0 讨论(0)
  • 2021-01-07 10:21

    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:

    Change:

    myText.innerHTML=ncxElement;
    

    To:

    myText.textContent=ncxElement;
    

    Change:

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

    To:

    <pre id="here">Begin!</pre>
    
    0 讨论(0)
  • 2021-01-07 10:23

    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.

    0 讨论(0)
提交回复
热议问题