2013-01-16 44 views
1
$(function() { 
    max = 25; 
    min = 1; 
    var i = 0; 

    do { 
     var match = Math.ceil(Math.random() * (max - min)- min); 

     $('td').each(function() { 
      i++; 
      console.log(match); 
      if (i == match) { 
       $(this).addClass('active'); 
      }  
     }) 
    } while ($('td.active').length == 10); 
}) 

我的問題是,我不返回10個隨機框,但只有一個。不顯示10個隨機框

回答

3

變化

} while ($('td.active').length == 10); 

} while ($('td.active').length < 10); 

while!= until

但是,如果您有少於10 td,你會無限循環。隨着i總是變大,它會經常破裂。

我想你想要這樣的:

$(function() { 
    var max = 25; // don't forget the "var", if you don't want to declare global variables 
    var min = 1; 
    do { 
     var match = Math.ceil(Math.random() * (max - min)- min); 
     $('td').eq(match).addClass('active'); 
    } while ($('td.active').length < 10); 
}) 
+1

當我改變瀏覽器崩潰 –

+0

@NikiLichev我還修復了另一個邏輯問題。請參閱編輯 –

0

試試這個:如果你確信自己是最低10 TD的

$(function() { 
    max = 25; 
    min = 1; 
    var i = 0; 
    var y=0; 

    do { 
     var match = Math.ceil(Math.random() * (max - min)- min); 

     $('td').each(function() { 
      i++; 
      console.log(match); 
      if (i == match) { 
       $(this).addClass('active'); 
       y++; 
      }  
     }) 
    } while (y<10); 
}) 
+0

但不起作用 –

+0

請參閱編輯中的答案 –

0

你還沒有說太多關於什麼代碼正在嘗試但除了其他建議,我認爲你也意味着

var match= Math.ceil(Math.random() * (max - min)+ min); 

注意'+ min'而不是o f減去。