我走在JavaScript類,這是我最後的項目。所以我是JavaScript新手。如何從一個函數傳遞變量值到另一個
應用程序請求的「盒子」的名稱,顏色和編號,以創建一個用戶。創建完成後,用戶可以點擊一個框來獲得一條消息,指出其ID,名稱,顏色以及框的頂部位置(XPOS)和左側位置(YPOS)。
我現在得到的是正確的,除了XPOS和YPOS出現爲未定義。如果我將display()函數中的this.xpos和this.ypos替換爲xpos和ypos,我會得到最後一個創建的框的值。
看來(我的未經訓練的眼睛),該ID和XPOS的創建,YPOS都差不多,應該工作一樣。那麼爲什麼ID顯示正確,而不是2位置變量?任何幫助,將不勝感激。
var name;
var id;
var color;
var amount;
var xpos = 0;
var ypos = 0;
function Box(id, name, color, xpos, ypos) { //element constructor function
this.id = id;
this.name = name;
this.color = color;
this.xpos = xpos;
this.ypos = ypos;
}
var box
var boxes = [];
var counter = 0;
window.onload = init;
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = generate;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
function generate() {
var dataForm = document.forms.data; //create var for the form collection
var nameInput = document.getElementById("name"); //get text input for name of Amazing Boxes
name = nameInput.value;
if(name == null || name == "") { //check to see if the input box is empty
alert("***Please enter valid text for a name***"); //if it is empty, alert user
nameInput.focus();
return;
}
var colorList = dataForm.elements.color; //get color choice for Amazing Boxes
color = colorList.value;
var radioPick = dataForm.elements.amount; //get the choice for number of Amazing Boxes
for(var i = 0; i < radioPick.length; i++) {
if (radioPick[i].checked) {
amount = radioPick[i].value;
}
}
if(amount == null || amount == "") { //test to make sure the user has checked an amount
alert("***Please choose an amount of boxes to be generated***");
return false;
}
else {
while(amount > 0) {
var sceneDiv = document.getElementById("scene");
xpos = Math.floor(Math.random() * (sceneDiv.offsetWidth-101)); //get a random number for box position
ypos = Math.floor(Math.random() * (sceneDiv.offsetHeight-101)); //get a random number for box position
id = counter;
var div = document.createElement("div"); //create new div element
div.setAttribute("id", id); //give the new div an id = to the var id
div.setAttribute("class", "box"); //give the new div a class = to box
div.innerText = name; //set text on box to the name
sceneDiv.appendChild(div); //make the new div a child element of the scene div
div.style.left = xpos + "px";
div.style.top = ypos + "px";
div.style.backgroundColor = color;
div.onclick = display;
counter ++; //increment counter var to get different box ids
amount--;
}
}
dataForm.reset();
nameInput.focus();
}
function display() {
alert("The ID of this box is " + this.id + " and it is named " + name + ". It's color is " + color +
" and is located at " + this.xpos + " and " + this.ypos + ".");
}
你有這個jsfiddle嗎? – Dalorzo
「盒子」應該是一個對象,而您應該能夠訪問您分配給它的變量?如果是這樣,請查看原型。 – pattmorter
@Dalorzo對不起,不知道那是什麼,所以沒有。 –