0

这是我的代码:

构造函数:

 function Box (//parameters) {  
  // code for constructor function  
  }

这是我获取创建新对象的值的地方:

  function getBoxValues() {
   //code to get values

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

这是我将框添加到页面的位置:

function addBox(newbox) {  
   for (var i = 0; i < newbox.number; i++) {                                 
   var scene = document.getElementById("scene");              
   var div = document.createElement("div"); 
   div.className += " " + "box"; 
   div.innerHTML += newbox.name; 
   div.style.backgroundColor = newbox.color; 
   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);                           
    } 
   return div;                        
  }

  display();

  function display(div) {
  div.innerHTML += "alert";
  console.log("alert");
  }

我的问题是我试图将 div 的值传递给显示函数,以便我可以写入对象的 innerHTML。我在控制台中不断收到一条消息,说 div 未定义。我认为这可能是范围的问题,但我无法弄清楚。

4

2 回答 2

1

你打电话display()时没有参数,当然它是未定义的;)

将适当的参数传递给函数调用,一切都会正常工作。

于 2013-01-16T21:32:26.363 回答
1

你的问题在这里:

display(); // <-- you call it with no argument

function display(div) {  // <-- there is 'div'
div.innerHTML += "alert"; // <-- undefined error
console.log("alert");
}
于 2013-01-16T21:32:34.333 回答