顔を生成し、監査された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