2

我試圖創建一個遊戲,用戶必須按特定順序放置每張卡。我可以將名稱拖放到可丟棄區域,但我將如何將特定卡分配給特定插槽。拖放到特定區域

這裏是我的js代碼:

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; 
    $('#cardPile').html(''); 
    $('#cardSlots').html(''); 

    // Create the pile of shuffled cards 

    var cards = ["Aiba", "Ninomiya", "Ohno", "Sakurai", "Matsumoto"]; 
    cards.sort(function() { return Math.random() - .5 }); 

    for (var i=0; i<cards.length; i++) { 
    $('<div>' + cards[i] + '</div>').data('img',i).appendTo('#cardPile').draggable({ 
     containment: '#content', 
     stack: '#cardPile div', 
     cursor: 'move', 
     revert: true 
    }); 
    } 


    // Create the card slots 
    var slots = [ ' ', ' ', ' ', ' ', ' ']; 
    for (var i=1; i<=slots.length; i++) { 
    $('<div>' + slots[i-1] + '</div>').data('number', i).appendTo( '#cardSlots').droppable({ 
     accept: '#cardPile div', 
     hoverClass: 'hovered', 
     drop: handleCardDrop 
    }); 
    } 

} 

function handleCardDrop(event, ui) { 
    var slotNumber = $(this).data('name'); 
    var cardNumber = ui.draggable.data('name'); 

    // 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 (slotNumber == cardNumber) { 
    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 == 10) { 
    $('#successMessage').show(); 
    $('#successMessage').animate({ 
     left: '380px', 
     top: '200px', 
     width: '400px', 
     height: '100px', 
     opacity: 1 
    }); 
    } 

} 
+0

你怎麼prentend知道,如果卡被放在正確與否插槽?圖像與名稱匹配? –

回答

0

如果你給一個唯一的ID給每個div都在那裏一卡(所以例如cardSlot1,cardSlot2 ......),你可以使用的document.getElementById(」 cardSlot1')。value來獲取卡的名字。

它看起來與此類似:

for (var i=0; i<cards.length; i++) { 
    $('<div id="cardSlot'+i+'">' + cards[i] + '</div>').data('img',i).appendTo('#cardPile').draggable({ 
     containment: '#content', 
     stack: '#cardPile div', 
     cursor: 'move', 
     revert: true 
    }); 
    }