这是我的代码:
构造函数:
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的值传递给display函数,以便我可以在object的innerHTML中编写。我一直在我的控制台中收到一条消息,指出div未定义。我认为这可能是范围问题,但我无法搞清楚。
答案 0 :(得分:1)
你在没有参数的情况下调用display()
,当然它是未定义的;)
将适当的参数传递给函数调用,它一切正常。
答案 1 :(得分:1)
你的问题在这里:
display(); // <-- you call it with no argument
function display(div) { // <-- there is 'div'
div.innerHTML += "alert"; // <-- undefined error
console.log("alert");
}