[英]InnerHTML- fetching from script
I am trying to display random numbers from 1 to 7. I do not want them to repeat and I want to display every number.我试图显示从 1 到 7 的随机数。我不希望它们重复,我想显示每个数字。 I've written my JS code inside
script
tag.我已经在
script
标签中编写了我的 JS 代码。 I want to get a random number whenever button
is clicked, instead I'm getting error我想在点击
button
时获得一个随机数,而不是我收到错误
Uncaught TypeError: Cannot set property 'innerHTML' of null
at grandom (fe.html:48)
at HTMLButtonElement.onclick (fe.html:25)
Below is my code下面是我的代码
<!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>
After document.write(...);
在
document.write(...);
there is no other elements in the page expect the passed text.除了传递的文本之外,页面中没有其他元素。
It is why when you trying to find then document.getElementById("demo")
it's cannot find, and return null
.这就是为什么当您尝试查找
document.getElementById("demo")
时找不到并返回null
。 (then throw error, when you trying to access its innerHTML
) (然后抛出错误,当您尝试访问其
innerHTML
)
If you trying to append something to the page you should use document.body.innerHTML += "..."
.如果您尝试向页面添加内容,则应使用
document.body.innerHTML += "..."
。
About the algorithm itself - you can use:关于算法本身 - 您可以使用:
[1,2,3,4,5,6,7].sort(function() { return .5 -Math.random();});
It will shuffle the array randomly.它会随机打乱数组。
Your document.write(..)
is breaking it.您的
document.write(..)
正在破坏它。
You can try:你可以试试:
document.body.innerHTML += '<br />';
document.getElementById("demo").innerHTML = `Question No : ${q[random]}`;
document.body.innerHTML += '<br />';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.