2011-05-08 66 views
0

我仍在为简单的JavaScript游戏而苦苦挣扎。这是我以前的问题:Simple javascript game, hide/show random square如何在不同的时间隐藏/显示多个广场

某些广场随机显示和隐藏几秒钟,你必须点击它们。我使用RaphaelJS来绘制广场和几个JQuery($ .each()函数)

我无法使用setInterval为每个方块工作的hide/show。通过Mishelle提出的功能看起来不错,但我得到了“这不是一个函数”的错误。我已经测试不同的东西,但我认为它不是那么明显:/

window.onload = function() { 

    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500); 
    // random function to for the x and y axis of the square 
    function random(min, max) { 
     return Math.floor(Math.random() * (max - min + 1)) + min; 
    } 
    var rectanglemain = paper.rect(0, 0, 500, 500).attr({fill: "white",}); 
    var win_click = 0; // set the var to count the click on the square 
    var recs = []; 
    for(var i = 0; i < 50; i++) { 
     var x = random(1,450); 
     var y = random(1,450); 
     var rec = paper.rect(x, y, 50, 50).attr({fill: 'blue'}); 
     recs.push(rec); // add the square in an array 
     recs[i].click(function() { 
     //counting the clicks 
     win_click = win_click + 1; 
     }) 
     function hideSquare() {recs[i].hide();} 
     hideSquare(); 
    } 
    rectanglemain.click(function() { 
     alert('you click on ' + win_click + ' squares'); 
    }); 
    /* here is a function made by Mishelle on my previous question, unfortunately I can't make it work (this is not a function error). 
function showBriefly (timeFromNow, duration) { 
     window.setTimeout(this.rec.show, timeFromNow); 
     window.setTimeout(this.rec.hide, timeFromNow + duration); 
     } 
    recs[2].showBriefly(1000, 3000); to test the function 
*/ 
} 

感谢您的帮助:)

回答

0

尝试

window.setTimeout(function(){this.rec.show();}, timeFromNow) 
+0

谢谢,我不得不删除“这个”。它只显示(第一个?)方块。我尝试与recs [我],但它不承认,但recs [2]的作品。如果添加单词“调试器”,则为 – Olivier 2011-05-08 16:57:55

+0

(没有引号)settimeout并运行firefox中的代码与萤火虫扩展功能打开,你会看到什么* this *是在指定的时间 – AndreasKnudsen 2011-05-08 16:58:48

+0

谢谢你的技巧,_this_引用“undefined”:/但它看起来像我越来越接近解决方案。 – Olivier 2011-05-08 17:17:47

0

在您的问题时只需来了,万一你读到这,你想知道是什么问题。 thisundefined回调之内,因此,你需要存储哪些矩形你在一个变量被提到(我把它叫做square),看到我的代码:

showBriefly: function(timeFromNow, duration) { 
    square = this.box; 
    setTimeout(function(){square.show();}, timeFromNow) 
    setTimeout(function(){square.hide();}, timeFromNow + duration) 
} 

干杯

+0

谢谢@maraujop我欣赏:) – Olivier 2011-08-03 10:23:57