使嵌套函数将id作为变量 - Javascript

时间:2016-03-23 01:46:56

标签: javascript object

我创建了一些函数并意识到我想要有一种方法可以多次调用它。

我如何重写函数,所以我也可以在第二个div上使用js?

https://jsfiddle.net/qj0q3zob/2/

这是原始代码

function createRectangles() {
    document.getElementById("homeactualcontent").innerHTML = " ";
    var count = 330;
        for(var i=0; i<count; i++){
            var newRect = document.createElement('div');
            newRect.className = 'rectangle';
            document.getElementById('homeactualcontent').appendChild(newRect);
    }


}

function colorIt() {
    var rects = document.querySelectorAll(".rectangle");
    for(var i=0; i<rects.length; i++){
        var a = Math.floor(Math.random() * 220)+30;
        var b = Math.floor(Math.random() * 30);
        var c = Math.floor(Math.random() * 220)+140;
        var d = Math.random()*1;
        rects[i].style.backgroundColor  = "rgb(" + a + "," + b + "," + c + ")";


    }
}


function moveIt() {
    var rects = document.querySelectorAll("#homeactualcontent .rectangle");
    var area = document.getElementById("homeactualcontent");
    for(var i = 0; i < rects.length; i++) {
        var a = Math.floor(Math.random()*96);
        var b = Math.floor(Math.random()*20);
        var c = Math.floor(Math.random()*90);
        var d = Math.floor(Math.random()*90);

        rects[i].style.position = "absolute";
        rects[i].style.left = a+"%";
        rects[i].style.right = b+"%";
        rects[i].style.top = c+"%";
        rects[i].style.bottom = d+"%";

    }
}

我认为这样可行,但我认为可能存在一些语法错误......或者我认为只是普通的错误。任何见解都会很棒!

编辑代码:

function rectz(x){

    function createRectangles(x) {
        document.getElementById(x).innerHTML = " ";
        var count = 330;
            for(var i=0; i<count; i++){
                var newRect = document.createElement('div');
                newRect.className = 'rectangle';
                document.getElementById(x).appendChild(newRect);
        }


    }

function colorIt() {
    var rects = document.querySelectorAll(".rectangle");
    for(var i=0; i<rects.length; i++){
        var a = Math.floor(Math.random() * 220)+30;
        var b = Math.floor(Math.random() * 30);
        var c = Math.floor(Math.random() * 220)+140;
        var d = Math.random()*1;
        rects[i].style.backgroundColor  = "rgb(" + a + "," + b + "," + c + ")";


    }
}


function moveIt(x) {
    var rects = document.querySelectorAll(" .rectangle");
    var area = document.getElementById(x);
    for(var i = 0; i < rects.length; i++) {
        var a = Math.floor(Math.random()*96);
        var b = Math.floor(Math.random()*20);
        var c = Math.floor(Math.random()*90);
        var d = Math.floor(Math.random()*90);

        rects[i].style.position = "absolute";
        rects[i].style.left = a+"%";
        rects[i].style.right = b+"%";
        rects[i].style.top = c+"%";
        rects[i].style.bottom = d+"%";

    }
}
}

0 个答案:

没有答案