2012-03-08 41 views
0

我正在构建一个简单的益智应用程序,并使用JavaScript library来拖放这些碎片。但我无法弄清楚如何检查所有部件是否在正确的位置。计算JavaScript中的事件

到目前为止,我已经得到了什么是

// create the draggable puzzle piece 
var p1=document.getElementById('piece1'); 
new webkit_draggable(p1); 
p1.className = 'ps1'; 

// create an array to count the pieces placed correctly 
var countArray = new Array(); 

// create the dropspot, link it to the puzzle piece and add an element to the array to count. Finally kill the dropspot 
var p1p1 = webkit_drop.add('droppiece1',{accept : ['ps1'], onDrop : function(){countArray.push("a");webkit_drop.remove('droppiece1')}}); 


// piece has been placed correctly. 
if(countArray.length = 1){ 
alert('Piece placed correctly'); 
}; 

我遇到的问题是,从计数功能火灾警报立即。 我该如何解决这个问题?

回答

5

更改最后三行:

// piece has been placed correctly. 
if(countArray.length == 1){ 
alert('Piece placed correctly'); 
}; 

你试图不是检查的平等分配。

编辑:那么,它仍然不适合你?在我看来,你正在onDrop上设置一个监听器,但是直到你完成之后(大概在onDrop事件被触发之前),你正在检查是否有任何东西被“删除”。看看如何不起作用? 如果您只想看到事件实际上正在触发,并且“a”实际上已经推送到您的数组中,您可以将最后三行移入回调中。像这样:

// create the draggable puzzle piece 
var p1 = document.getElementById('piece1'); 
new webkit_draggable(p1); 
p1.className = 'ps1'; 

// create an array to count the pieces placed correctly 
var countArray = new Array(); 

// create the dropspot, link it to the puzzle piece and add an element to the array to count. Finally kill the dropspot 
var p1p1 = webkit_drop.add('droppiece1', {accept: ['ps1'], onDrop: function() { 
    countArray.push("a"); 
    webkit_drop.remove('droppiece1'); 

    // piece has been placed correctly. 
    if (countArray.length == 1) { 
     alert('Piece placed correctly'); 
    } 
}}); 

我还没有真正测试过,但这里是取出所有WebKit的东西,用一个简单的点击取代降的版本:如果您点击红色框http://jsfiddle.net/kajic/snJMr/1/

,那么当你放下这件作品时,你预计会在你的ipad应用上发生什么?

+0

对!对不起,这真是愚蠢的我。我试过使用==,但现在警报根本没有发射。感谢您及时的回复。 – 2012-03-08 17:49:26

+0

仍然没有运气?看我的编辑。 – 2012-03-08 18:28:39

+0

明天进行测试,但我认为你有一些东西。每当一块作品正确放置时,我可以检查计数。当所有东西都放置正确后,警报将会触发。如果我正确阅读它。 非常感谢! – 2012-03-08 23:38:03

4

if(countArray.length = 1){ 

if(countArray.length == 1){ 
        // ^^ use comparison, not assignment 

第一行分配 1至countArray.length,其解析为1,这是truthy你应该改变。