2015-12-06 35 views
0

为了使这相当简单,我在代码中的评论说明我正在努力完成。我的代码执行似乎不会继续计算,直到它找到一个空类的.wrap,这正是我想要做的。也许有人可以帮我弄清楚如何扩展无限检查,最终找到一个未定义类的open .wrap。JavaScript随机数寻找hasClass,不存在

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"); 
} 
+0

你是一个循环中运行这个或者这是所有的代码? –

+0

@NickKenens它是递归函数。 – jcubic

+0

@jcubic打字后我注意到了,我的不好。如果没有给出任何参数,使用循环递归函数有什么好处?对我来说似乎有点野蛮。 –

回答

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"); 
} 

或者它可能是简单的“智能”地使用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')