我正在嘗試創建一個代碼,該代碼生成面並將它們顯示爲經過審計的Coursera.com課程的一部分。有些變量會在函數之外生成,我想將其傳遞給它,然後將其刪除。我嘗試:將變量傳遞給函數
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theImg = document.createElement("img");
theImg.src = "smile.png";
function generateFaces(numberOfFaces, theLeftSide, theImg) {
for (i = 0; i < numberOfFaces; i++) {
var leftPosition = Math.floor(Math.random() * 400);
var topPosition = Math.floor(Math.random() * 400);
theImg.style.left = leftPosition + "px";
theImg.style.top = topPosition + "px";
theLeftSide.appendChild(theImg.cloneNode());
};
var theRightSide = document.getElementById("rightSide");
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages.cloneNode(true));
return leftSideImages;
}
window.onload = generateFaces;
,因爲我並沒有定義在
window.onload = generateFaces;
接下來的任何變量這感覺不對,我嘗試了按鈕
<input id="clickMe" type="button" value="clickme" onclick="generateFaces(numberOfFaces, theLeftSide, theImg);" />
在一推正確的方向將不勝感激。如果我在函數中定義變量,代碼將起作用,這是迄今爲止的成就!
爲什麼你要在本地和外部定義這些變量作爲全球? – tadman
對不起,我的意思是如果我將它們定義在函數內而不是外部,我的代碼就可以工作。這是我最初測試函數的方式,但現在我想在其他地方使用一些變量。 – Jacob