javascript随机数查找不存在的hasClass

时间:2015-12-06 14:47:22

标签: javascript jquery

为了使这个相当简单,我在代码中的评论说出我想要完成的事情。执行时我的代码似乎不会继续计算,直到它找到一个带有空类的.wrap,这正是我想要做的。也许有人可以帮我弄清楚如何扩展无限检查,最终找到一个尚未定义类的开放.wrap。

function computerMove(){
    //returns number between 1-9
    var rand = Math.floor((Math.random() * 9) + 1);
    console.log(rand);

    //checks for if .wrap has class of x and if it does it should get another number
    var check = $(".board .wrap:nth-child("+rand+")").hasClass("x");


    if(check){
    console.log("checking") 
    var rand = Math.floor((Math.random() * 9) + 1); 
    //I believe this should work and repeat the function
    computerMove();
    }
    else{
    $(".board .wrap:nth-child("+rand+")").addClass("o");
}

1 个答案:

答案 0 :(得分:1)

不,不必使用递归功能。使用循环。

function computerMove(){
    var check;
    var rand;
    do {
        //returns number between 1-9
        rand = Math.floor((Math.random() * 9) + 1);
        console.log(rand);
        check = $(".board .wrap:nth-child("+rand+")").hasClass("x");
    } while (check)

    $(".board .wrap:nth-child("+rand+")").addClass("o");
}

或者它可以更简单到#34;聪明地"使用jQuery选择器

// Find all elements that do not have x class
var items = $(".board .wrap:not(.x)")
// Get a random element
var target = items[Math.floor(Math.random()*items.length)];
// Add o class to the target
$(target).addClass('o')
相关问题