在HTML页面上显示对象的动态数量


<!DOCTYPE html>
<html>
<head>
<title>my site</title>
<script>
// javascript code here
// generates a random number, X, from 1 to 10 each time this page is requested
// displays X number of "blue-object" 
</script>
<style>
/*css if needed */
</style>
</head>
<body>
<div class = "blue-object" style="background:blue; margin:20px">This is an instance of a blue object</div>
<div class = "blue-object" style="background:blue; margin:20px">This is an instance of a blue object</div>
</body>
</html>

所以目前上面的页面是静态的。它总是显示"蓝色对象"类的2个对象。我需要让它充满活力。因此,为了简单起见,这些对象显示的数字是一个随机生成的数字。那么怎样才能做到这一点呢?

开始:

<!DOCTYPE html>
<html>
<head>
<title>my site</title>
<style>
div{
background-color:blue;
margin:20px;
}
</style>
</head>
<body id="main">
<script> 
var desiredText="Hey there! change me ;)";
//You can just change the variable to your desired text and that's it :)
var randomRepeater=function(desiredText){
var iterator=Math.floor(Math.random() * 10);
console.log("will create "+iterator+" divs this time :) ");
for(var i=0;i<iterator;i++){
var div = document.createElement("div");
div.innerHTML = desiredText.toString();
document.getElementById("main").appendChild(div);
}
}
randomRepeater(desiredText);
</script>
</body>
</html>

最新更新