2012-03-08 74 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你應該改變。