2009-05-13 4 views
2

아래 코드를 두렵게하지 마십시오. 질문은 정말 간단합니다. 두 줄만 문제를 일으키고 있습니다.jquery : 변수 NaN 반환

왜 내 코드가 NaN 오류 코드를 생성합니까? 하나의 변수 값을 다른 변수 값에서 뺀 결과이므로 요소의 위치가 정확합니다.

변수는 jQuery position()에서 값을 얻었습니다.이 값은 정수 여야합니다.

확인 라인이 라인 :

// For some reason NaN error code gets generated when line below gets executed. 
var posTop = Startpos.top - Stoppos.top; 
var posLeft = Startpos.left - Stoppos.left; 

전체 코드 :

<!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" lang="en" xml:lang="en"> 
<head> 
    <meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" /> 
    <title>Drag drop 1</title> 
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> 
    <script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
     var Startpos = new Array; 
     var Stoppos = new Array; 

     // Make images draggable. 
     $(".item").draggable({ 

      // Elements cannot go outside #container 
      containment: 'parent', 

      // Make sure the element can only be dropped in a grid. 
      grid: [150,150], 

      // Find original position of dragged image. 
      start: function(event, ui) { 

       // Make sure picture always are on top when dragged (z-index). 
       $(this).css({'z-index' : '100'}); 

       // Show start dragged position of image. 
       Startpos = $(this).position(); 
       $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top); 
      }, 

      // Find position where image is dropped. 
      stop: function(event, ui) { 

       // Revert to default layer position when dropped (z-index). 
       $(this).css({'z-index' : '10'}); 

       // Show dropped position. 
       Stoppos = $(this).position(); 
       $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top); 
      } 
     }); 
     $(".item").droppable({ 
      drop: function(event, ui) { 

       // Dragged image gets swapped with dropped on image. 
       var prev_position = "#" + $(this).attr('id'); 
       // For some reason NaN error code gets generated when line below gets executed. 
       var posTop = Startpos.top - Stoppos.top; 
       var posLeft = Startpos.left - Stoppos.left; 

       // Below variables will work. But unfortunately they 
       // doesn't give the correct numbers for the purpose. 
       // var posTop = Startpos.top; 
       // var posLeft = Startpos.left; 

       $(prev_position).css({'top' : posTop, 'left' : posLeft}); 

       $("div#test").text("Passed variables. Top: " + posTop + " left: " + posLeft); 
      } 
     }); 
    }); 
    </script> 
    <style> 
    body { 

    } 
    #container { 
     position:relative; 
     width:480px; 
     border:1px solid #000; 
    } 
    .item { 
     position:relative; 
     width:150px; 
     height:150px; 
     z-index:10; 
    } 
    </style> 
</head> 
<body> 
    <div id="container"> 
     <img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" /><img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" /><img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" /><img id="productid_4" src="images/pic4.jpg" class="item" alt="" title="" /><img id="productid_5" src="images/pic5.jpg" class="item" alt="" title="" /><img id="productid_6" src="images/pic6.jpg" class="item" alt="" title="" /><img id="productid_7" src="images/pic7.jpg" class="item" alt="" title="" /><img id="productid_8" src="images/pic8.jpg" class="item" alt="" title="" /><img id="productid_9" src="images/pic9.jpg" class="item" alt="" title="" /> 
    </div> 
    <div style="clear:both;"></div> 
    <div id="start">Waiting...</div> 
    <div id="stop">Waiting...</div> 
    <div id="hover">Waiting...</div> 
    <div id="stop2">Waiting...</div> 
    <div id="test">Waiting...</div> 
</body> 
</html> 

답변

4

문제는 drappable.drop()가 이고 draggable.stop()보다 먼저 발생한다는 것입니다. 따라서 스토퍼는 아직 계산되지 않았습니다.

이 문제를 처리하는 한 가지 방법은 끌리는 항목을 간단히 추적하고 droppable.drop()에서 그 위치를 계산하는 것입니다. 예 : (코드의 하위 집합), "끌기"개체를 확인하십시오.

$(document).ready(function() { 
     var Startpos = new Array; 
     var Stoppos = new Array; 
     var Dragging = null; 

     // Make images draggable. 
     $(".item").draggable({ 

       // Elements cannot go outside #container 
       containment: 'parent', 

       // Make sure the element can only be dropped in a grid. 
       grid: [150,150], 

       // Find original position of dragged image. 
       start: function(event, ui) { 
         Dragging=this; 
         // Make sure picture always are on top when dragged (z-index). 
         $(this).css({'z-index' : '100'}); 

         // Show start dragged position of image. 
         Startpos = $(this).position(); 
         $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top); 
       }, 

       // Find position where image is dropped. 
       stop: function(event, ui) { 
         // Revert to default layer position when dropped (z-index). 
         $(this).css({'z-index' : '10'}); 

         // Show dropped position. 
         Stoppos = $(this).position(); 
         $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top); 
         Dragging=null; 
       } 
     }); 

그러나이 문제를 해결하는 데는 다른 방법이있을 수 있습니다.

+0

Stoppos와 Startpos를 배열로 초기화하는 것이 무엇이겠습니까? 초기화하지 않거나 null을 설정하지 않는 이유는 무엇입니까? – jlarson

+0

흠 ... 저를 대체하는 것이 무엇입니까? var posTop = Startpos.top - Stoppos.top, var에 posLeft = Startpos.left - Stoppos.left, 으로 : var에 수술 후 = Startpos.top; VAR posLeft = Startpos.left;, 숫자가 내가 원하는 것이 아니더라도 작동 할 것입니다. Stoppos 및 Startpos를 초기화하면 – Cudos

+0

이 전역 범위에서 사용할 수 있습니다. 하지만 나는 자바 스크립트에서 전역 변수에 익숙하지 않다. 방금 작업 한 것처럼 보였습니다. – Cudos

1

지금까지 내가()는 jQuery를 기능이없는 위치를 알고.

대신을 시도해보십시오

Startpos = $(this).offset(); 

당신은 다음 위쪽 및 왼쪽 속성에 액세스 할 수 있어야합니다.

+0

실제로 position()을 사용할 수 있습니다. 링크 참조 : http://docs.jquery.com/CSS/position 반환합니까? 요소의 위치 – Cudos

0

이것이 문제의 원인이되는 라인입니까?

는 수술 후에 유효한 정수/Double 값을 반환 - - "Stoppos.top var에 수술 후 = Startpos.top"

당신은 확인하시기 바랍니다 수 있습니까? 저는 지난 주에 제 프로젝트 중 하나를 코딩하고 있었고 동일한 NaN 문제가있었습니다. Integer 값을 파싱하려고 시도했는데 성공했습니다. 당신은 수학적 계산을하고 있기 때문에

, 당신이 그들을 빼기 전에

때때로, 해결책은 아주 간단합니다, 더블/지능에 값을 구문 분석을 시도하고 우리는 이상을 복잡하게하는 경향이있다.

구문 분석이 작동하지 않으면 배열에서 올바른 값을 전달하지 못하는 것일 수 있습니다. Startpos [0]과 같은 것을 시도해보십시오. 위로

호프가 도움이 되었길 바랍니다, 행운을 비네!

+0

행운이없는 parseInt()를 시도했습니다 : var posTop = parseInt (Startpos.top - Stoppos.top); 또는 var posTop = parseInt (Startpos.top) - parseInt (Stoppos.top); – Cudos

0

이 계산을 수행 할 때 Startpos 또는 Stoppos는 여전히 빈 배열입니다.

잘못된 기본 설정을 (0, 0)으로 설정해보십시오. 이탈로 인해 발생하는 상황을 쉽게 추적 할 수 있습니다.나 퍼즐 무엇

0

이 작동한다는 것입니다 :

교체 :와

var posTop = Startpos.top - Stoppos.top; 
var posLeft = Startpos.left - Stoppos.left; 

:

var posTop = Startpos.top; 
var posLeft = Startpos.left; 

숫자가 내가 원하지 않는 어떤 경우에도 작동합니다. simples 빼기가 어떤 이유로 유효하지 않은 것 같습니다.

+0

Stoppos.top & Stoppos.left는 항상 숫자로 초기화됩니까? –

+0

예. 문제는 다른 곳에있다. – Cudos

0

도움 주셔서 감사합니다. :)

발견.

Stoppos = $(this).position(); 

에 있어야하지 :

$(".item").draggable({ 
stop: function(event, ui) { 

하지만 그 대신에 :

$(".item").droppable({ 
drop: function(event, ui) { 

전체 코드 :

<!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" lang="en" xml:lang="en"> 
<head> 
    <meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" /> 
    <title>Drag drop 1</title> 
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> 
    <script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
     var Startpos = null; 
     var Stoppos = null; 

     // Make images draggable. 
     $(".item").draggable({ 

      // Elements cannot go outside #container 
      containment: 'parent', 

      // Make sure the element can only be dropped in a grid. 
      grid: [150,150], 

      // Find original position of dragged image. 
      start: function(event, ui) { 

       // Make sure picture always are on top when dragged (z-index). 
       $(this).css({'z-index' : '100'}); 

       // Show start dragged position of image. 
       Startpos = $(this).position(); 
       $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top); 
      }, 

      // Find position where image is dropped. 
      stop: function(event, ui) { 

       // Revert to default layer position when dropped (z-index). 
       $(this).css({'z-index' : '10'}); 
      } 
     }); 
     $(".item").droppable({ 
      drop: function(event, ui) { 

       // Dragged image gets swapped with dropped on image. 
       var prev_position = "#" + $(this).attr('id'); 
       Stoppos = $(this).position(); 
       var posTop = Startpos.top - Stoppos.top; 
       var posLeft = Startpos.left - Stoppos.left; 
       $(prev_position).css({'top' : posTop, 'left' : posLeft}); 

       // Test window 
       $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top); 
       $("div#test").text("Passed variables. Top: " + posTop + " left: " + posLeft); 
      } 
     }); 
    }); 
    </script> 
    <style> 
    body { 

    } 
    #container { 
     position:relative; 
     width:480px; 
     border:1px solid #000; 
    } 
    .item { 
     position:relative; 
     width:150px; 
     height:150px; 
     z-index:10; 
    } 
    </style> 
</head> 
<body> 
    <div id="container"> 
     <img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" /><img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" /><img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" /><img id="productid_4" src="images/pic4.jpg" class="item" alt="" title="" /><img id="productid_5" src="images/pic5.jpg" class="item" alt="" title="" /><img id="productid_6" src="images/pic6.jpg" class="item" alt="" title="" /><img id="productid_7" src="images/pic7.jpg" class="item" alt="" title="" /><img id="productid_8" src="images/pic8.jpg" class="item" alt="" title="" /><img id="productid_9" src="images/pic9.jpg" class="item" alt="" title="" /> 
    </div> 
    <div style="clear:both;"></div> 
    <div id="start">Waiting...</div> 
    <div id="stop">Waiting...</div> 
    <div id="hover">Waiting...</div> 
    <div id="stop2">Waiting...</div> 
    <div id="test">Waiting...</div> 
</body> 
</html> 

지금 내가 얼마나 파악해야 도착 그들이 한 번 이상 움직 였을 때 바로 이미지의 배치. position : relative가 draggables에 자동으로 추가되어 위치 계산에 문제가있는 것처럼 보입니다. (