0

I have a question about javascript. My problem is that I have 9 div containers and an selector () with numbers from 1 to 9. What I would like to have is ONE function that chooses the quantity, which is chosen in the selector, and hides the number of divs with the visibility option. The function should really should hide the number of the selector and not that the function hides two times the same random div. The divs are in one class and have the ids like id1, id2 and id3.

Hope you understand anything, because my English really sucks in this topic.

Thanks Nicolas

4

1 回答 1

0

您的代码中有一些错误:

if (zahl[y].style.visibility = 'hidden') {

你需要document.getElementById(zahl[y])而不仅仅是zahl[y],你需要用来==比较值而不是=。此外,您正在将可见性设置为隐藏,然后检查它是否隐藏,如果您想以相反的方式进行操作。和,

i - 1;

应该是i--;。如果您修复了这些问题,代码将正常工作,如此处所示

然而,一些进一步的改进也是可能的——当你可以使用时,不需要定义所有的索引getElementsByClassName

function hide(anzahl) {
    var cubes = document.getElementsByClassName('cube');
    for (var i = 0; i < cubes.length; i++) {
        cubes[i].style.visibility = '';
    }
    for (var i = 0; i < anzahl;) {
        var y = Math.floor(Math.random() * 9);
        if (cubes[y].style.visibility == '') {
            cubes[y].style.visibility = 'hidden';
            i++;
        }
    }
}

jsfiddle

于 2013-08-12T01:04:45.143 回答