2017-01-12 1 views
0

타이머에서 html span 요소의 텍스트를 변경해야합니다. 타이머가 잘 작동하지만 스팬 내용을 변경하지 않아도됩니다. 내가 여기 실종 무엇jQuery 함수에 전달 요소

$(element).text(hour); 

:

문제에있다?

HTML은 : 여기

<span id="mytimer">00:00</span> 

내 JS이다

function loaded(selector, callback){ 
     $(function() { 
      callback($(selector)); 
     }); 
     $(document).on('DOMNodeInserted', selector, function() { 
      callback($(this)); 
     }); 
    }; 

    function setupTimer(element, duration, interval) { 
     var start = Date.now(), 
      diff, 
      minutes, 
      seconds; 
     clearInterval(window.mytimer); 
     function timer() { 
      diff = duration - (((Date.now() - start)/1000) | 0); 
      minutes = (diff/60) | 0; 
      seconds = (diff % 60) | 0; 
      if (minutes < 0) { 
       minutes = 0; 
      } 
      if (seconds < 0) { 
       seconds = 0; 
      } 
      minutes = minutes < 10 ? "0" + minutes : minutes; 
      seconds = seconds < 10 ? "0" + seconds : seconds; 
      hour=minutes + ":" + seconds; 
      $(element).text(hour); 
      if (window.mytimer != null & diff < 0) { 
       clearInterval(window.mytimer); 
      } 
     }; 
     timer(); 
     window.mytimer = setInterval(timer, interval * 1000); 
    }; 

    loaded('#mytimer', function(el){ 
      setupTimer(el,100,1); 
    }); 
+0

이 요소는, 당신은 단지'element.text (시간)을 사용할 수 있습니다 이미 선택의 jQuery 객체입니다 함께 넣어,'필요는 두 번 – Kaddath

+1

@Daniel Corzo 왜 것이라고 도움을 선택 없습니다? 'time'은 텍스트를 포함하고'.text (argument)'는 전달 된 인자를 포함하는 텍스트 노드로 요소의 자식을 대체하는 유효한 Jquery 메소드입니다. – VKK

+0

@DanielCorzo, 왜'.html()'이 작동 하겠지만'.text()'는 작동하지 않을까요? –

답변

3

먼저,이에 나는 위의 의견에 언급, 당신의로드 방법을 분리 Kaddath의 하나 추가 대답은, 그가 올 (또는 그것의 적어도 일부).

왜?

  • DOMNodeInserted는 사용되지 않으며 성능에 부정적인 영향을 가지고 있습니다.
  • 이 요소의 내용 (HTML/텍스트)을 변경할 때마다 삽입 된 새 이벤트가 트리거되므로 타이머가 작동하지 않는 것입니다.

당신이 당신의 코멘트 beow에 설명 된대로 정말 "대기"해야하는 경우, 당신은 DOMNodeInserted 논리를 "대체"mutationobserver를 사용할 수 있습니다. 나는 작은 example

$().ready(function() { 

    function setupTimer(element, duration, interval) { 
    var start = Date.now(), 
     diff, 
     minutes, 
     seconds; 
    clearInterval(window.mytimer); 
    function timer() { 
     diff = duration - (((Date.now() - start)/1000) | 0); 
     minutes = (diff/60) | 0; 
     seconds = (diff % 60) | 0; 
     if (minutes < 0) { 
      minutes = 0; 
     } 
     if (seconds < 0) { 
      seconds = 0; 
     } 
     minutes = minutes < 10 ? "0" + minutes : minutes; 
     seconds = seconds < 10 ? "0" + seconds : seconds; 
     hour=minutes + ":" + seconds; 
     element.text(hour); 
     if (window.mytimer != null & diff < 0) { 
      clearInterval(window.mytimer); 
     } 
    }; 
    timer(); 
    window.mytimer = setInterval(timer, interval * 1000); 
    }; 

    // simply run your method here (in case DOM element exists) 
    // setupTimer($('#mytimer'),100,1); 

    // in case your element is not there you can 
    // observe the document for changes like this... 
    var observer = new MutationObserver(function(mutations) { 
     mutations.forEach(function(mutation) { 
     var newNodes = mutation.addedNodes; // DOM NodeList 
     if(newNodes !== null) { // If there are new nodes added 
      var $nodes = $(newNodes); // jQuery set 
      $nodes.each(function() { 
       var $node = $(this); 
       // looking for your element 
       if($node.attr('id') === 'mytimer') { 
        // do your action 
        setupTimer($('#mytimer'),100,1); 
        // in case you do not need it any longer 
        observer.disconnect(); 
       } 
      }); 
     } 
     });  
    }); 

    // Configuration of the observer: 
    // might be possible to reduce this in your case 
    var config = { 
     attributes: true, 
     childList: true, 
     characterData: true 
    }; 

    // the target has to be an existing DOM node 
    // adapt this to your needs... 
    var target = document.body; 

    // Pass in the target node, as well as the observer options 
    observer.observe(target, config); 

}); 
+0

안녕하세요. mytimer가 런타임에 작성되었으므로 저에게 효과가 없습니다. 나는 그것을 언급하는 것을 잊었다. –

+0

Axel에게 감사드립니다. "on"및 위임에 대해 몇 가지 알고 있습니다. 그러나 스팬 (타이머 포함)이 dinamically 생성 된 후 타이머를 트리거하는 데 On 메서드를 사용해야합니까? –

+0

@LuizAlves 그래서 요소를 만들 때 setupTimer 메서드를 호출하지 않으시겠습니까? –

0

삽입 한 DOM과 일부 제거가 재로 간격을 일으키는 여기

내 코드 왜냐하면 당신이``text()`를 할 때, 당신은 요소를 삽입하기 때문입니다.

function loaded(selector, callback){ 
    $(function() { 
     callback($(selector)); 
    }); 
    /*$(document).on('DOMNodeInserted', selector, function() { 
     callback($(this)); 
    });*/ 
}; 

확인이 바이올린 : https://jsfiddle.net/rzaeg38g/

+0

좋아,하지만 내 애플 리케이션의 다른 부분을 깰거야? 나는 런타임에 생성 된 다른 HTML 페이지에서 많은 dom 요소를 가지고 있으며 콜백을 사용해야합니다. –

+0

코드를 setuptimer로 변경하면 : \t /*$(element).text(hora);*/ \t $ ('# mytimer'). 텍스트 (hora); 그것은 작동합니다. 그래서 나는 당신의 대답이 옳은 이유를 모르겠다. –

+0

axel michel의 대답을 참조하십시오. 그는 또한 더 나은 구조화 된 코드를 제공합니다. – Kaddath

관련 문제