向/从函数传递变量

雅各布

我正在尝试创建一个代码,该代码生成人脸并将其显示为经过审核的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);" />

向正确方向的推动将不胜感激。如果我在函数中定义变量,代码将起作用,到目前为止,这是一个成就!

格里高

我认为您遇到的问题是,您正在尝试在加载页面之前访问dom元素。

var theLeftSide = document.getElementById("leftSide");

请尝试在需要的函数中声明它,因为无论如何它都不会在函数外部使用。

var numberOfFaces = 5;
var theImg = document.createElement("img");
theImg.src = "smile.png";    

function generateFaces(numberOfFaces, theLeftSide, theImg) {

        var theLeftSide = document.getElementById("leftSide");

        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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章