我在这里有一个对象构造函数:

function Box (id, name, color, number, coordinates) {
   this.id = id;
   this.name = name;
   this.color = color;
   this.number = number;
   this.coordinates = coordinates;

   this.add = function(howMany) {
   }
  }


我在这里有一个函数的一部分,在该函数中,我获得了用户使用单选按钮选择的数值(5、10或15)。

  function getBoxValues() {
   var nameInput = document.getElementById("name");
   var name = nameInput.value;

   var numbersArray = dataForm.elements.amount;
   for (var i = 0; i < numbersArray.length; i++) {
   if (numbersArray[i].checked) {
    number = numbersArray[i].value;

   if (name == null || name == "") {
     alert("Please enter a name for your box");
     return;
   }
   else {
    var newbox = new Box("id", name, color, number, "coordinates");
    boxes.push(newbox);
    addBox(newbox);

   var data = document.getElementById("dataForm");
    data.reset();
   }


稍后,我使用此功能向页面添加框:

  function addBox(newbox) {
   var scene = document.getElementById("scene");
   var div = document.createElement("div");
   div.innerHTML += newbox.name;
   var x = Math.floor(Math.random() * (scene.offsetWidth-101));
   var y = Math.floor(Math.random() * (scene.offsetHeight-101));
   div.style.left = x + "px";
   div.style.top = y + "px";
   scene.appendChild(div);
   newbox.add(number);
   for (var i = 0; i < howMany; i++) {
   console.log("added");
    addBox(newbox);
    }
  }


我的问题是我想向网页添加与用户使用单选按钮选择的框相同数量的框。到目前为止,我的控制台日志告诉我“添加”循环遍历“ number”的次数。但是,我不知道如何更改代码,以便为number的值创建新的框。我是新手,因此给您造成的任何困惑我深表歉意。将不胜感激。

最佳答案

function addBoxes () {
    var i;

    for (i=0; i < number; i += 1) {
        // create box
        addBox(newBox);
    }
}

关于javascript - 使用方法javascript在页面上添加框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14329138/

10-14 14:47
查看更多