简体   繁体   中英

Drag and Drop Jquery function not working in site

I'm having a problem getting my code to work when it's incororated into a live site. The fiddle works just fine, but when I include the identical code in a webpage, I can't get the function to load/work at all.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Drag and Drop Assignment</title>
<!doctype html>

<link rel="stylesheet" href="styles/style1.css"/>

<style>

.drop{
float: left;
width: 350px;
height: 400px;
border: 3px solid blue;
background-image: url("http://debsiepalmer.com/images/tardis 2.jpg");
background-repeat: no-repeat;
background-size:  cover;
}
#right{float: left;
width: 350px;
height: 400px;
border: 3px solid red;
}

</style>

<script src="draganddrop.js" ></script>
<script src="http://code.jquery.com/jquery-2.0.2.js" ></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" ></script>
<script type="text/javascript">
$ (init);

function image(id, image1) {
this.id = id;
this.image1 = image1;
}

$('#deal').click(function () {dealAll(
dealCard(randomCard()));
});

 $(function() {
$( "#draggable" ).draggable({ containment: "#left"});
});

function init() {
 $('.drop').droppable( {
 drop: handleDropEvent
  } ); 
$("img").draggable();
}

// global variables
var cardsInDeck = new Array();
var numberOfCardsInDeck = 15;
cardsInDeck[0] = "Ace";
cardsInDeck[1] = "Grace";
cardsInDeck[2] = "Susan";
cardsInDeck[3] = "Ian";
cardsInDeck[4] = "Barbara";
cardsInDeck[5] = "Brigadier";
cardsInDeck[6] = "Romana I";
cardsInDeck[7] = "K9";
cardsInDeck[8] = "Tegan";
cardsInDeck[9] = "Jamie";
cardsInDeck[10] = "Sarah Jane";
cardsInDeck[11] = "Jo";
cardsInDeck[12] = "Romana II";
cardsInDeck[13] = "Yates";
cardsInDeck[14] = "Leela";
var cardsDealt = new Array();

function dealAll(){
var z=0;
 for (z=0;z<5;z++) {
   cardsDealt[z] = new Image(z,dealCard(randomCard()));
}
}

function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var $img = new Image();
$img.src = "images/Companions/" + cardsInDeck[i] + ".jpg";
// Here I set the ID of the object
$img.id=cardsInDeck[i];
$img.class='drag';
document.body.appendChild($img);
$('#'+$img.id).draggable();
removeCard(i);
return $img;
}
// deal randomly - works

function randomCard() {
return Math.floor(Math.random() * numberOfCardsInDeck);  
}

function removeCard(c)
{

for (j=c; j <= numberOfCardsInDeck - 2; j++)
{
    cardsInDeck[j] = cardsInDeck[j+1];
}
numberOfCardsInDeck--;
numberOfCardsInDeck--;
numberOfCardsInDeck--;
}
function handleDropEvent( event, ui ) {
alert("Fantastic!  You chose " + ui.draggable.attr("id") + " to be your companion.");
// Here I want the id of the dropped object
}
</script>
</head>

<body>
<div id="container" div style="width:750px; margin:0 auto;">
<div id="page_content" style="left: 0px; top: 0px; width: 750px" class="auto-style8">

<!--Begin Assignment 10 --->
<div id="left" class="drop">
<img id="tardis" ></img>
</div>
<input type="button" value="Get Companions" id="deal" />
<div id="content" style="left: 0px; top: 0px; width: 750px">
</div>
</div>
</div>
</body>
</html>

It's supposed to generate 5 images, one of which can be selected to be dropped onto the target and generate an alert with the id of the image being dropped. Like I said, it works just fine in the fiddle - and the code is identical on the web page, so I don't understand what I'm doing wrong.

fiddle: http://jsfiddle.net/reaglin/FUvT8/6/

I ordered some code...and for me it worked

// global variables
var cardsInDeck = [],
    numberOfCardsInDeck = 5;
cardsInDeck[0] = "Ace";
cardsInDeck[1] = "Grace";
cardsInDeck[2] = "Susan";
cardsInDeck[3] = "Ian";
cardsInDeck[4] = "Barbara";
cardsInDeck[5] = "Brigadier";
cardsInDeck[6] = "Romana I";
cardsInDeck[7] = "K9";
cardsInDeck[8] = "Tegan";
cardsInDeck[9] = "Jamie";
cardsInDeck[10] = "Sarah Jane";
cardsInDeck[11] = "Jo";
cardsInDeck[12] = "Romana II";
cardsInDeck[13] = "Yates";
cardsInDeck[14] = "Leela";


//load "init" when document it's ready
$(document).on('ready',init);

function init() { 
  $( "#draggable" ).draggable({ containment: "#left"});
  $('.drop').droppable( {drop: handleDropEvent}); 
}

$('#deal').click(function () {
    dealAll();
});
$('#reset-pictures').click(function(){
    $('img.drag').remove();
    numberOfCardsInDeck = 5;
});
// deal 5 cards at once - works
function dealAll(){
    // 5 cards max, no repeat cards
    while(numberOfCardsInDeck){
        var rand = randomCard();
        dealCard(rand);
    }

}

//deal cards - works
function dealCard(i) {
    //create id, remove space id
    var id_picture = (cardsInDeck[i] +'-'+i).replace(/\s/g, '');
    //validate not exist image
    if (!!$('img#'+id_picture).length) {
        return;
     }

    var $img = $('<img/>', { src : "http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg", id : id_picture, class : 'drag', 'data-info': cardsInDeck[i]
                          })
    $('body').append($img);
    $('img.drag').draggable();
    numberOfCardsInDeck--;

}
// deal randomly - works
function randomCard() {
   return Math.floor(Math.random() * cardsInDeck.length);  
}


// this is what to do when card drops in tardis
function handleDropEvent( event, ui ) {
    alert(ui.draggable.attr("data-info"));
}

DEMO

JSFinddle

Are you linking to JQuery correctly in the live version? Sometimes when moving from a development area to a live system the references mess up, you can find out if a reference is working or not by viewing the source code and entering in the link into the URL.

This is how you fix it: Take all the javascript (from $ (init) to the alert()) and place it at the bottom of the loaded page, inside the body, after all the elements. This ensures that the javascript knows what named elements you are talking about.

I would like to emphasise that this is not a tip for writing good javascript. The problem arises because it's bad javascript to begin with. Well written pages do not rely on the position of the code within the page, rather the opposite in fact.

Postscript: I literally did the following: I came here after googling "drag and drop"; I didn't fully read the actual question; I went to the jfiddle; I copied all the code for my own purposes; I couldn't get it to work; I fixed it (just trial and error really); I fixed the bug which is still present even on the jfiddle page; and then I came back here to find out what the original query had been!

The other bug is the fact that you can't drag the images of "Romana I", "Romana II" and "Sarah Jane". As the code makes the array values the id of the image elements, maybe others can instantly spot what causes that problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM