2014-02-11 7 views
0

내 HTML 문서에는 하나의 외부 스크립트와 하나의 내부 스크립트가 있습니다. 나는 그들을 하나의 외부 자바 스크립트 파일에 결합하고 싶었다. 불행히도 내부 하나를 내부에 넣으면 내부 스크립트 기능이 작동하지 않습니다. 나는 왜 그것이 실용적인지 알 수 없다.스크립트 결합 자바 스크립트

아래의 결합 된 스크립트는 내부 및 내부로 구분됩니다.

//INTERNAL SCRIPT 
    var x = 0, y = 0, 
     vx = 0, vy = 0, 
     ax = 0, ay = 0; 

    var points; 


    var sphere = document.getElementById("sphere"); 
    var counting = false; 
    var counter = 0; 
    var numberOne; 

    if (window.DeviceMotionEvent != undefined) { 
     window.ondevicemotion = function(e) { 

      ax = event.accelerationIncludingGravity.x * 5; 
      ay = event.accelerationIncludingGravity.y * 5; 

      document.getElementById("counterSpan").innerHTML = Math.round(counter*10)/10; 
      //document.getElementById("accelerationX").innerHTML = Math.round(e.accelerationIncludingGravity.x * 10)/10; 
      //document.getElementById("accelerationY").innerHTML = Math.round(e.accelerationIncludingGravity.y * 10)/10; 
      //document.getElementById("accelerationZ").innerHTML = Math.round(e.accelerationIncludingGravity.z * 10)/10; 

      var moveX = Math.round(e.accelerationIncludingGravity.x * 10)/10; 
      //var moveY = Math.round(e.accelerationIncludingGravity.y * 10)/10; 
      //var moveZ = Math.round(e.accelerationIncludingGravity.z * 10)/10; 

      if(moveX > 5 || moveX < -5) { 
       counting = true; 
       //alert(counting); 
       if(counter < 100){counter+=0.01;} 
       } 




      if (e.rotationRate) { 
       //document.getElementById("rotationAlpha").innerHTML = Math.round(e.rotationRate.alpha * 10)/10; 
       //document.getElementById("rotationBeta").innerHTML = Math.round(e.rotationRate.beta * 10)/10; 
       //document.getElementById("rotationGamma").innerHTML = Math.round(e.rotationRate.gamma * 10)/10; 
      }  
     } 


    $("#btnEnergize").click(function() { 

     numberOne = $("#numberOne").val(); 
      alert(numberOne); 
      localStorage.setItem('points',numberOne); 

      if (numberOne <= counter){ 
      counter-=numberOne; 
      } 
      else { 
      alert("Not enough Energize points");  
      } 


    }); 

     setInterval(function() { 
      var landscapeOrientation = window.innerWidth/window.innerHeight > 1; 
      if (landscapeOrientation) { 
       vx = vx + ay; 
       vy = vy + ax; 
      } else { 
       vy = vy - ay; 
       vx = vx + ax; 
      } 
      vx = vx * 0.98; 
      vy = vy * 0.98; 
      y = parseInt(y + vy/50); 
      x = parseInt(x + vx/50); 

      boundingBoxCheck(); 

      //sphere.style.top = y + "px"; 
      //sphere.style.left = x + "px"; 

     }, 25); 
    } 


    function boundingBoxCheck(){ 
     if (x<0) { x = 0; vx = -vx; } 
     if (y<0) { y = 0; vy = -vy; } 
     if (x>document.documentElement.clientWidth-20) { x = document.documentElement.clientWidth-20; vx = -vx; } 
     if (y>document.documentElement.clientHeight-20) { y = document.documentElement.clientHeight-20; vy = -vy; } 

    } 

    function minmax(value, min, max) 
    { 
     if(parseInt(value) < 0 || isNaN(value)) 
      return 0; 
     else if(parseInt(value) > 100) 
      return 100; 
     else return value; 

    } 



    //EXTERNAL SCRIPT 

    jQuery(function($){ 



     var $overlay = $('.overlay'), 
      resize = true, 
      map; 
     var service; 
     var marker = []; 
     var pos; 
     var infowindow; 
     var placeLoc 
     var markerValue = []; 
     var markers 


    function initialize() { 
     /*var mapOptions = { 
     zoom: 8, 
     center: new google.maps.LatLng(-34.397, 150.644), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     map = new google.maps.Map(document.getElementById('map-canvas'), 
      mapOptions); 

    }*/ 
    var mapOptions = { 
     zoom: 15 
     }; 
     map = new google.maps.Map(document.getElementById('map-canvas'), 
      mapOptions); 

     // Try HTML5 geolocation 
     if(navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position) { 

       var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); 

      var request = { 
      location:pos, 
      center:pos, 
      radius:1000, 

     }; 

     infowindow = new google.maps.InfoWindow(); 
     var service = new google.maps.places.PlacesService(map); 
     service.nearbySearch(request,callback); 
      pos = new google.maps.LatLng(position.coords.latitude, 
              position.coords.longitude); 


      infowindow = new google.maps.InfoWindow({ 
      map: map, 
      position: pos, 
      content: 'You Are Here' 
      }); 
      $('#findMe').data('pos',pos); 

      map.setCenter(pos); 
     }, function() { 
      handleNoGeolocation(true); 
     }); 
     } else { 
     // Browser doesn't support Geolocation 
     handleNoGeolocation(false); 
     } 



     function callback(results, status) { 
      markers = []; 
     if (status == google.maps.places.PlacesServiceStatus.OK) { 
     for (var i = 0; i < results.length; i++) { 
      markers.push(createMarker(results[i])); 
     } 
     } 
     $('#findMe').data('markers',markers); 
    } 
    } 



    function createMarker(place) { 


     placeLoc = place.geometry.location; 

     var marker = new google.maps.Marker({ 
     map: map, 
     position: place.geometry.location, 
     icon: { 
      path: google.maps.SymbolPath.CIRCLE, 
      scale: 8, 
      fillColor:'00a14b', 
      fillOpacity:0.3, 
      fillStroke: '00a14b',  
      strokeWeight:4, 
      strokeOpacity: 0.7 
     }, 




     }); 


     google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent(place.name); 
     infowindow.open(map, this); 
     }); 
     return marker; 
    } 

    function handleNoGeolocation(errorFlag) { 
     if (errorFlag) { 
     var content = 'Error: The Geolocation service failed.'; 
     } else { 
     var content = 'Error: Your browser doesn\'t support geolocation.'; 
     } 

     var options = { 
     map: map, 
     position: new google.maps.LatLng(60, 105), 
     content: content 
     }; 

     var infowindow = new google.maps.InfoWindow(options); 
     map.setCenter(options.position); 
    } 

    google.maps.event.addDomListener(window, 'load', initialize); 

    $('#show').click(function(){ 

     $overlay.show(); 

     if (resize){ 
     google.maps.event.trigger(map, 'resize'); 
     resize = false; 
     } 

    }); 

    $('.overlay-bg').click(function(){ 

     $overlay.hide(); 

    }); 




    $("#findMe").click(function() { 



     var pos  = $(this).data('pos'), 
      markers = $(this).data('markers'), 
      closest; 


     if(!pos || !markers){ 
     return; 
     } 

     $.each(markers,function(){ 
     var distance=google.maps.geometry.spherical 
         .computeDistanceBetween(this.getPosition(),pos); 
     if(!closest || closest.distance > distance){ 
      closest={marker:this, 
        distance:distance} 
     } 
     }); 
     if(closest){ 
     //closest.marker will be the nearest marker, do something with it 
     //here we simply trigger a click, which will open the InfoWindow 
     google.maps.event.trigger(closest.marker,'click') 


     var Loc2 = closest.marker.getPosition(); 


     for (var i=0; i<markers.length; i++) { 
      var Loc1 = markers[i].getPosition() 



      if (Loc1.equals(Loc2)){ 
       console.log("its the same"); 
       console.log("marker array Location 1 " + Loc1 + " marker " + i); 
       console.log("closest Location 2 " +Loc2); 

       markerValue[i] = numberOne; 

       console.log("marker " + i + " now equals " + markerValue[i]); 

      } 

     } 
     } 

    }); 


    }); 
+0

작동하지 않는 것에 대한 추가 정보를 제공해 줄 수 있습니까? 줄 번호가 주어지면 오류가 발생합니다. 그것은보아야 할 곳에 대한 힌트없이 소화하기위한 많은 텍스트입니다. – snollygolly

+0

내부 코드를'jQuery (function ($) {..}) '안에 넣으십시오. 내 생각 엔 DOM로드 문제 인 –

+0

은 항상 DOM과 상호 작용하는 모든 코드가 외부 스크립트와 마찬가지로 window.onload 또는 jQuery 준비 이벤트 처리기인지 확인합니다. – thescientist

답변

1

외부 코드를 살펴보면 바로 jQuery 준비 이벤트 핸들러에 있습니다. 내부 코드가 DOM과 상호 작용하기 때문에 동일한 이벤트 핸들러 컨텍스트에서도 실행되고 있는지 확인해야합니다.

내부 코드가 페이지 맨 아래에 있거나 아마 준비 이벤트 핸들러 내에있을 가능성이 있으며이를 고려하지 않은 것 같습니다.

+0

나는 그것을 고쳤다 고 생각합니다. 모든 외부 변수를 맨 위로 이동하면 전체 스크립트에 대해 전역 적이어야합니다. 그래서 스크립트간에 변수들과 상호 작용하는 함수를 추가하고 싶다면 그렇게 할 수 있을까요? –

+0

@DanKristianWilliams 일반적으로 모든 함수 선언과 필요한 전역 요소 참조 변수를 onload/ready 외부에 정의합니다. 모든 초기화 코드는 일반적으로 이러한 DOM 참조를 가져 와서 캐시 한 다음 이벤트 처리기를 할당합니다. 가능한 경우 init 코드를 깨끗하고 작게 유지하고 함수 호출에 위임합니다. 다른 모든 것은 일반적으로 addEventListener를 사용하여 할당 할 준비가 된 이벤트 핸들러입니다. 기본적으로 부트 스트랩 코드 일뿐입니다. – thescientist

관련 문제