InnerHTML- 从脚本中获取

InnerHTML- fetching from script

我正在尝试显示从 1 到 7 的随机数。我不想让它们重复,我想显示每个数字。我已经在 script 标签内编写了我的 JS 代码。我想在单击 button 时获得一个随机数,但我收到错误消息

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at grandom (fe.html:48)
    at HTMLButtonElement.onclick (fe.html:25)

下面是我的代码

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Goplan Project Selection</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/4.1/examples/sign-in/">

    <!-- Bootstrap core CSS -->
    <link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">



  </head>

  <body>
  <div class="jumbotron">
  <div class="text-center">
        <img src="cissoiree.jpg" width="80px" height="80px">
    <h1 style="text-size:300em">Go-Plan</h1></div></div>
    <div style="padding-top:20px;" class="text-center">
      <button class="btn-lg btn-primary" onclick="grandom()">Click!</button>
      <p id="demo"><p>
    </div>
    <script type="text/javascript"> 

    function grandom()
    {
    var q=[2,3,1,5,4,7,6];
    var x=7;
    var i;
    x=q.length;
    var random;
            while(1)
            {

                random = Math.floor(Math.random()*x);
                if(random<=q.length)
                break;
            }
            document.write("<br>");
            document.write("Question No : " + q[random] );
            if(q.length!=1)
            <!--document.write("<input type=button value=click here onclick=grandom();><br>");-->
            document.getElementById("demo").innerHTML = q[random];
            q.splice(random,1);     
            document.write("<br>");
     }
     </script> 
    </body>
</html>


document.write(...); 之后页面中没有其他元素需要传递的文本。

这就是为什么当您尝试查找时 document.getElementById("demo") 找不到,并且 return null。 (然后抛出错误,当你试图访问它时 innerHTML

如果你想在页面上附加一些东西,你应该使用 document.body.innerHTML += "..."

关于算法本身——你可以使用:

[1,2,3,4,5,6,7].sort(function() { return .5 -Math.random();});

它会随机打乱数组。

你的 document.write(..) 坏了。

你可以试试:

document.body.innerHTML += '<br />';
document.getElementById("demo").innerHTML = `Question No : ${q[random]}`;
document.body.innerHTML += '<br />';