无法将值传递给函数参数javascript
这是我的密码: 构造函数函数:无法将值传递给函数参数javascript,javascript,object,parameters,Javascript,Object,Parameters,这是我的密码: 构造函数函数: function Box (//parameters) { // code for constructor function } 这里是我获取值以创建新对象的地方: function getBoxValues() { //code to get values if (name == null || name == "") { alert("Please enter a name fo
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");
}
函数addBox(newbox){
对于(var i=0;i
我的问题是,我试图将div的值传递到display函数中,以便可以在对象的innerHTML中写入。我在控制台中不断收到一条消息,说div未定义。我认为这可能是范围的问题,但我很难弄清楚 您正在调用没有参数的
display()
,当然它是未定义的;)
将适当的参数传递给函数调用,它就会正常工作。您的问题在于:
display(); // <-- you call it with no argument
function display(div) { // <-- there is 'div'
div.innerHTML += "alert"; // <-- undefined error
console.log("alert");
}
display();//谢谢,但问题是我必须移动显示器(div);进入addBox(newbox)函数。它只在其中一个框中显示“警报”。