在jquery中使用拖放操作,无法得到正确的答案

时间:2014-06-24 17:23:33

标签: javascript jquery

嗨,这是我第一次发帖,如果我错过任何事情就道歉。 我想要做的是随机化一个字符串数组,然后让用户将它们放在正确的框中。我已完成随机化,但我无法计算出允许用户将其放在正确位置的代码。我可以得到它可以放入任何盒子或根本没有 我不是程序员,这是关于学习的最终论文的一部分,所以我试图保持简单 这是我的剧本。提前致谢:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script type="text/javascript">

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

  // Create the pile of shuffled words
  var newwords = [ 'me', 'you', 'him', 'her','it','them', 'those', 'test', 'apple', 'orange'];
  newwords.sort( function() { return Math.random() - .5 } );


  for ( var i=0; i<10; i++ ) 
  {
    $('<div>' + newwords[i] + '</div>').data( 'right', newwords[i] ).attr( 'id', 'card'+newwords[i] ).appendTo( '#wordPile' ).draggable( {
      containment: '#content',
      stack: '#wordPile div',
      cursor: 'move',
      revert: true
    } );
  }

  // Create the word slots
  var words = [ 'me', 'you', 'him', 'her','it','them', 'those', 'test', 'apple', 'orange'];
  for ( var i=1; i<=10; i++ ) 
  {
    $('<div>' + words[i-1] + '</div>').data( 'right', i ).appendTo( '#cardSlots' ).droppable( {
      accept: '#wordPile div',
      hoverClass: 'hovered',
      drop: handleCardDrop
    } );
  }

}

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

  // 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 words  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
    } );
  }

}

</script>

1 个答案:

答案 0 :(得分:0)

您是否考虑过将代码包装在dom ready事件中:

 $(function(){
    //script here
 });

$(document).ready(function(){
   //script here
});