2017-03-24 1 views
-2

카운트를 시작하고 단추를 클릭 할 때 중지 할 타이머를 만들려고합니다. here에서 수정 한 코드가 온라인에 있지만 jQuery 게시 메서드를 호출 할 때 불법 호출 오류가 발생합니다. 나는 그것이 범위 문제라고 확신한다. 그러나 나는 그 주변의 최선의 방법이 확실치 않다. 내 수정 된 코드는 아래와 같습니다.개체 내에서 jQuery 호출

var timer={ 
 

 
init:function(id){ 
 
    this[id]={ 
 
    obj:document.getElementById(id) 
 
    } 
 
}, 
 

 
start:function(id){ 
 
    var obj=this[id]; 
 
    obj.srt=new Date(); 
 
    clearTimeout(obj.to); 
 
    this.tick(id); 
 
    $("#climbTimer").unbind(); 
 
    $('#climbTimer').click(function(){timer.finalStop('climbTimer'); return false;}); 
 
    
 
    if ($('#'+id).html().indexOf('Start') != -1) 
 
     $('#'+id).html('Stop Ascend<br><span id="elapsedTime">0.00</span>'); 
 
}, 
 

 
stop:function(id){ 
 
    \t clearTimeout(this[id].to); 
 
}, 
 
    
 
finalStop:function(id){ 
 
\t clearTimeout(this[id].to); 
 
\t 
 
\t $.post('php/climbTime.php', {team: document.getElementById('team').value, roundNum: document.getElementById('round').value, time: document.getElementById('elapsedTime')}); 
 
}, 
 

 
tick:function(id){ 
 
    this.stop(id); 
 
    var obj=this[id],sec=(new Date()-obj.srt)/1000,min=Math.floor(sec/60),sec=sec%60; 
 
    $('#elapsedTime').html(sec>9?sec:''+sec); 
 
    obj.to=setTimeout(function(){ timer.tick(id); },100); 
 
} 
 
    
 
\t 
 
}

+0

점점 더 자세한 오류 메시지가 나타날 수 있습니까? – amphetamachine

+2

'timer.finalStop ('climbTimer') 대신'timer.finalStop (id);'가 필요합니다. 또한 더 이상 사용되지 않는'.unbind()'를 사용하지 말고'.off ('click')'을 사용하십시오. – trincot

답변

3

몇 가지 문제 :

  • document.getElementById('elapsedTime')$.post에 개체 속성 값으로 전달됩니다 이것은 DOM 객체이며, jQuery를 그것을에는 직렬화하기 위해 노력하고, 모든 프로퍼티에 액세스 . 그러면 오류가 발생합니다. 대신 당신은 textContent 부동산 취득해야합니다

    $.post('php/climbTime.php', { 
        team: document.getElementById('team').value, 
        roundNum: document.getElementById('round').value, 
        time: document.getElementById('elapsedTime').textContent // <--- 
    }); 
    
  • 당신은 timer.finalStop('climbTimer') 전화를하지만은 버튼의 이름이 아니라 당신과 당신의 타이머를 시작하는 데 사용되는 ID입니다. 후자는 1.7

    마지막으로 jQuery를하기 때문에 사용되지 않습니다 당신이 제대로 코드를 들여 경우 수 더 나은 자리 오류,

    timer.finalStop(id); 
    

는 또한 .off('click') 대신 .unbind()를 사용하는 것이 좋습니다 것입니다 : 당신은 할 필요가 긴 하나의 라이너는 피하십시오. value 속성은 긴 줄의 맨 오른쪽에 없습니다.

+0

도움을 주셔서 감사합니다. 누락 값 속성을 보지 못했지만 실제로는 원하는 값이 아니라는 것을 깨닫게되었지만 elapsedTime은 범위 였기 때문에 HTML 내용이 있음을 알게되었습니다. –

+0

당신은 환영합니다 ;-) 이제 코드에서 생성 된 스팬입니다. NB : 텍스트 처리시'.textContent'를'.innerHTML'보다 사용하는 것이 낫습니다. 그렇지 않으면 원치 않는' ','&'등을 얻을 수 있습니다. – trincot

관련 문제