2013-11-25 46 views
0

我是Javascript新手,但是我從一個數字數組中自定義了一個代碼,以便在其中我想識別目標以完成遊戲的字母數組。Draggable對象無法識別目標Javascript jquery

代碼中的錯誤是它掉到了任何目標上,這意味着它不能識別相應的目標。

The original codecode that I customized

var correctCards = 0; 
$(init); 

function init() { 
    // Hide the success message 
    $('#successMessage').hide(); 
    $('#successMessage').css({ 
     left: '580px', 
     top: '250px', 
     width: 0, 
     height: 0 
    }); 

    // Reset the game 
    correctCards = 0; 
    $('#vocalPile').html(''); 
    $('#vocalSlots').html(''); 

    // Create the pile of shuffled cards 
    var vocales = ["a", 'e','i' , 'o', 'u']; 
    vocales.sort(function() { return Math.random() - .5 }); 

    for (var i=0; i<5; i++) { 
     $('<div>' + vocales[i] + '</div>') 
      .data('vocal', vocales[i]) 
      .attr('id', 'vocal'+vocales[i]) 
      .appendTo('#vocalPile') 
      .draggable({ 
       containment: '#content', 
       stack: '#vocalPile div', 
       cursor: 'move', 
       revert: true 
      }); 
    } 

    // Create the card slots 
    var words = ['a', 'e', 'i', 'o', 'u']; 
    for (var i = 1; i <= 5; i++) { 
     $('<div>' + words[i-1] + '</div>') 
      .data('vocal', i) 
      .appendTo('#vocalSlots') 
      .droppable({ 
       accept: '#vocalPile div', 
       hoverClass: 'hovered', 
       drop: handleCardDrop 
      }); 
    } 

} 

function handleCardDrop(event, ui) { 
    var slotVocal = $(this).data('vocales'); 
    var cardVocal = ui.draggable.data('vocales'); 

    // If the card was dropped to the correct slot, 
    // change the card colour, position it directly 
    // on top of the slot, and prevent it being dragged 
    // again 

    if (slotVocal == cardVocal) { 
     ui.draggable.addClass('correct'); 
     ui.draggable.draggable('disable'); 
     $(this).droppable('disable'); 
     ui.draggable.position({ of: $(this), my: 'left top', at: 'left top' }); 
     ui.draggable.draggable('option', 'revert', false); 
     correctCards++; 
    } 

    // If all the cards have been placed correctly then display a message 
    // and reset the cards for another go 

    if (correctCards == 5) { 
     $('#successMessage').show(); 
     $('#successMessage').animate({ 
      left: '380px', 
      top: '200px', 
      width: '400px', 
      height: '100px', 
      opacity: 1 
     }); 
    } 
} 

我認爲在通過函數傳遞的參數中存在錯誤。但我不知道如何改變他們在if ==。

謝謝:)

PS。一組元音不是我想要實現的元音的數字。

回答

0

你有

在創建卡插槽的錯誤:

$('<div>' + words[i-1] + '</div>') 
.data('vocal',words[i-1])... 

使用陣列

handleCardDrop功能修復數據屬性聲樂沒有vocales如在你的小提琴

function handleCardDrop(event, ui) { 
    var slotVocal = $(this).data('vocal'); 
    var cardVocal = ui.draggable.data('vocal'); 

工作fiddle