2013-09-27 2 views
0

난 그냥 단순히 페이드 전환과 함께 사진을 바꿔 일부 OO 자바 스크립트를 할 노력하고있어와 스와핑 이미지,하지만 아무것도 페이지가로드 될 때 발생합니다.은 OO 자바 스크립트 디버깅 - 전이시

내 모든 이미지는 조 _ #. JPG, #는 숫자 이름이 지정됩니다. 여기

내 imagesJS.js이 파일입니다

여기
//GLOBALS 
var delay = 5000; 
var opacityDelay = 100; 
var pathBeginning = "images\joe\Joe_"; 
var pathEnding = ".jpg"; 

//IMAGE CLASS 
function imageObj(id, start, end, initDelay) { 

    this.obj = document.getElementById(id); 

    this.cur = start; 
    this.start = start; 
    this.end = end; 

    this.initDelay = initDelay; 
    this.opacity = 1; 


    this.fadeIn = function() { 
     if(this.opacity < 1) { 
      this.opacity = this.opacity + 0.1; 
      obj.style.opacity = this.opacity; 
      setTimeout(this.fadeIn(), opacityDelay); 
     } 
    } 

    this.nextImage = function() { 

     if(this.cur == this.end) { 
      this.cur = this.start; 
     } 
     else { 
      this.cur++; 
     } 

     obj.src = pathBeginning + this.cur.toString() + pathEnding; 

     this.fadeIn(); 
    } 

    this.fadeOut = function() { 
     if(this.opacity > 0.5) { 
      this.opacity = this.opacity - 0.1; 
      obj.style.opacity = this.opacity; 
      setTimeout(this.fadeOut(), opacityDelay); 
     } 
     else { 
      this.nextImage(); 
     } 
    } 

    this.process = function() { 
     setInterval(this.fadeOut(), delay + Math.floor(Math.random()*delay)); 
    } 
} 

imageObj.prototype.startProcess = function() { 
    setTimeout(this.process(), this.initDelay); 
} 


//IMAGE OBJECTS 
var img1 = imageObj('img1', 1, 5, 5000); 
img1.startProcess(); 

내가 HTML 페이지에있는 모든 것을 포함하는 방법입니다

<head> 
    <!-- Links/Scripts --> 
    <link rel="stylesheet" type="text/css" href="style.css"/> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <script src="myJavascript.js" type="text/javascript"></script> 
    <script src="imagesJS.js" type="text/javascript"></script> 

그리고 이것은 myJavascript.js 파일입니다 (어쩌면 무언가가) :

// GLOBAL VARIABLES 
var body = $('.body'); 

//***********// 
// On Load // 
//***********// 
$(document).ready(function(){ 
    //MenuItem Color Change 
    $('.menuItem').mouseover(function(){ 
     $(this).css({"color":"#6699ff"}) 
    }).mouseout(function(){ 
     $(this).css({"color":"black"}) 
    }); 
}); 

개체를 onLoad 함수에 넣어야합니까? 나에게 문제가있는 것 같지 않아. 미리 감사드립니다.

// ############################################ ####################### 업데이트 1

다음은 net.uk에서 조언을 수정 한 후의 코드입니다. .... 어떤 아이디어를

//GLOBALS 
var delay = 5000; 
var opacityDelay = 100; 
var pathBeginning = "images\joe\Joe_"; 
var pathEnding = ".jpg"; 

//IMAGE CLASS 
function imageObj(id, start, end, initDelay) { 

    this.obj = document.getElementById(id); 

    this.cur = start; 
    this.start = start; 
    this.end = end; 

    this.initDelay = initDelay; 
    this.opacity = 1; 


    this.fadeIn = function() { 
     if(this.opacity < 1) { 
      this.opacity = this.opacity + 0.1; 
      this.obj.style.opacity = this.opacity; 
      setTimeout(fadeIn, opacityDelay); 
     } 
    } 

    this.nextImage = function() { 

     if(this.cur == this.end) { 
      this.cur = this.start; 
     } 
     else { 
      this.cur++; 
     } 

     this.obj.src = pathBeginning + this.cur.toString() + pathEnding; 

     this.fadeIn(); 
    } 

    this.fadeOut = function() { 
     if(this.opacity > 0.5) { 
      this.opacity = this.opacity - 0.1; 
      this.obj.style.opacity = this.opacity; 
      setTimeout(fadeOut, opacityDelay); 
     } 
     else { 
      this.nextImage(); 
     } 
    } 

    this.process = function() { 
     var self = this; 
     self.fadeOut(); 
     setInterval(function() {self.fadeOut();}, delay+Math.floor(Math.random()*delay)); 
    } 
} 

imageObj.prototype.startProcess = function() { 
    var self = this; 
    setTimeout(function() {self.process();}, this.initDelay); 
} 

//IMAGE OBJECTS 
var img1 = new imageObj('img1', 1, 5, 5000); 
img1.startProcess(); 

불행하게도, 그것은 여전히 ​​작동하지 않습니다 - 아래 .sweet이 링크 Using setTimeout() within a JavaScript class function

에서 일부 범위 문제는 코드 업데이트?

// ############################################ #################### 솔루션 업데이트

생성 및 추가해야했습니다. 내 다른 자바 스크립트 파일에서 onLoad 함수에서 startProcess 함수 호출.

다음은 솔루션 코드 : 모든 도움말 net.uk.sweet에 대한

//GLOBALS 
var delay = 5000; 
var opacityDelay = 100; 
var pathBeginning = "images\\joe\\Joe_"; 
var pathEnding = ".jpg"; 

//IMAGE CLASS 
function imageObj(id, start, end, initDelay) { 

    this.obj = document.getElementById(id); 
    this.cur = start; 
    this.start = start; 
    this.end = end; 
    this.initDelay = initDelay; 
    this.opacity = 1; 

    this.fadeIn = function() { 
     var self = this; 
     if(this.opacity < 1) { 
      this.opacity = this.opacity + 0.1; 
      this.obj.style.opacity = this.opacity; 
      setTimeout(function() {self.fadeIn();}, opacityDelay); 
     } 
    } 

    this.nextImage = function() { 

     if(this.cur == this.end) { 
      this.cur = this.start; 
     } 
     else { 
      this.cur++; 
     } 

     this.obj.src = pathBeginning + this.cur.toString() + pathEnding; 
     this.fadeIn(); 
    } 

    this.fadeOut = function() { 
     var self = this; 
     if(this.opacity > 0.2) { 
      this.opacity = this.opacity - 0.1; 
      this.obj.style.opacity = this.opacity; 
      setTimeout(function() {self.fadeOut();}, opacityDelay); 
     } 
     else { 
      self.nextImage(); 
     } 
    } 

    this.process = function() { 
     var self = this; 
     self.fadeOut(); 
     setInterval(function() {self.fadeOut();}, delay + Math.floor(Math.random()*delay)); 
    } 
} 

imageObj.prototype.startProcess = function() { 
    var self = this; 
    setTimeout(function() {self.process();}, this.initDelay); 
} 

감사합니다! 는 범위와 크롬 개발 도구에 대해 많은 것을 배웠다! 희망 나는 언젠가 다른 사람을 도울 수 있기를 바랍니다!

답변

2

좋아하는 브라우저 (here's how)에서 디버깅 도구에 익숙해지면 큰 호응을 얻으실 수 있습니다. 콘솔은 프로그램의 흐름을 따르는 데 도움이되도록 입력 한 모든 로그 문과 코드의 오류 세부 정보를 출력하며 중단 점과 같은 고급 디버깅 기능을 사용하여 코드를 단계별로 실행하고 오류가 발생한 위치를 확인할 수 있습니다.

그렇다면 코드에 몇 가지 명백한 문제가 있음을 알 수 있습니다. 함수 정의를 사용하여 자바 스크립트에서 새 개체를 인스턴스화 할 때

, 당신은 new 키워드를 사용해야합니다

var img1 = new imageObj('img1', 1, 5, 5000); 

당신은 당신이 참조를 전달하는 대신 직접 함수를 호출하고 setTimeout 사용할 때마다. 이것은 함수가 즉시 실행되고 시간 초과가 완료되지 않았 음을 의미합니다.예를 들어, 다음과 같이 당신이 당신의 startProcess 방법에 코드를 업데이트해야합니다 setTimeout를 사용하는 경우

// Note the missing parenthesis. You should pass the function to 
// setTimeout by reference instead of invoking the function directly. 
setTimeout(this.process, this.initDelay); 

하지만를 ... 당신은 또한 범위와 관련된 문제로 실행하고 (좋은 설명 this stackoverflow thread에 답 참조) . 당신의 방법은 범위가 아닌 글로벌 윈도우 객체로 인스턴스로 호출되는 것을 보장하기 위해 폐쇄를 사용해보십시오 :

imageObj.prototype.startProcess = function() { 
    var self = this; 
    setTimeout(function() { 
     self.process(); 
    }, this.initDelay); 
} 

은 내가 obj 변수가 범위를 벗어나 당신이 그것을 참조하는 방법이라고 생각합니다. 다음을 사용하여 액세스 해보십시오.

this.fadeIn = function() { 

    // Sending information to the console is a very simple way of debugging 
    // your program. You can even use it to trace the value of variables! 
    console.log('In here! Current image opacity is:', this.opacity); 

    if(this.opacity < 1) { 
     this.opacity = this.opacity + 0.1; 
     this.obj.style.opacity = this.opacity; 
     setTimeout(this.fadeIn(), opacityDelay); 
    } 
} 
+0

감사합니다. 이것은 괄호로 함수를 호출한다는 것을 확실히 이해할 수 있습니다. 반면에 나는 함수에 대한 참조를 전달하지 않고있다. 그러나 다른 버그가있는 것으로 보입니다. 하지만 고마워! –

+0

내가 말했듯이 디버깅 도구를 사용하여 문제를 추적 한 다음 문제를 이해하지 못하면 다시 질문을합니다. 나는 다른 모습을 보였고 더 많은 오류를 발견했지만 일반적으로 사람들은 자신을 먼저 도우려고하지 않으면 코드를 디버깅 할 준비가되지 않습니다. –

+0

저는 Chrome Dev Tools를 사용하여 디버깅을 해왔습니다.이 프로세스는 init.Delay 후에 'process'함수가 호출되면 this.fadeOut() 함수가 범위에서 인식되지 않는다고 알려줍니다. 특히이 오류 :'code' Uncaught TypeError : Object [object global] 'fadeOut''code' 메서드가 없습니다 –