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

时间:2020-03-06 00:35:15

标签: javascript html css

<!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个“蓝色对象”类的对象。 我需要使其动态。因此,为简单起见,这些对象显示的数字是随机生成的数字。那怎么办呢?

1 个答案:

答案 0 :(得分:1)

您在这里:

<!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>
相关问题