将参数传递给函数javascript的麻烦

时间:2013-01-15 18:04:29

标签: javascript object methods parameters

这是我的对象构造函数:

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) {       //add method with parameter howMany
    }
}

这是我设置数字和名称值的函数:

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

    var numbersArray = dataForm.elements.amount;      //gets value from radio button
    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);                                           
    }
} 

这是我用来向页面添加框的功能:

function addBox(newbox) {                                   
    var scene = document.getElementById("scene");              
    var div = document.createElement("div");                   
    div.className += " " + "box"; 
    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();
    }                          
}

我正在尝试将number属性的值传递给newbox.add(),以便我可以告诉函数创建等于newbox.number的次数的框。因此,如果用户从单选按钮中选择5,则会创建5个框。我一直在看这段代码,而且我也是初学者,所以我很容易错过一些明显的东西。我很感激你的帮助。谢谢。

0 个答案:

没有答案