可拖动对象无法识别目标Javascript Jquery

时间:2013-11-25 19:21:08

标签: javascript jquery

我是Javascript的新手,但我将数字数组中的代码自定义为一系列字母,我想在其中识别目标以完成游戏。

代码中的错误是它掉落到任何目标,这意味着它无法识别相应的目标。

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。元数组是不是我想要实现的元数。

1 个答案:

答案 0 :(得分:0)

中有错误

在创建卡位:

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

使用数组

handleCardDrop 功能

将数据属性修复为 vocal 而不是 vocales ,就像在你的小提琴中一样

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

工作fiddle