2014-02-08 2 views
0

Я делаю текстовое поле, подобное принтеру, которое может отображать письмо по одному. Я мог бы понять, что это просто использовать функцию и загрузить его как просто как:Как сделать текстовое поле в виде принтера, используя javascript OOP

HTML ---

<div id="myTypingText"></div> 

JS ---

<script> 
    var myString = "Place your string data here, and as much as you like."; 
    var myArray = myString.split(""); 
    var loopTimer; 
    function frameLooper() { 
     if(myArray.length > 0) { 
      document.getElementById("myTypingText").innerHTML += myArray.shift(); 
     } else { 
      clearTimeout(loopTimer); 
        return false; 
     } 
     loopTimer = setTimeout('frameLooper()',70); 
    } 
    frameLooper(); 
    </script> 

Но я хочу, чтобы сделать более продвинутый, я хотите, чтобы пользователь мог изменить скорость и изменить текст, поэтому я написал следующее, но это пошло не так, почему? помогите мне .thx.

HTML ----

<div id="myTypingText"></div> 
    <p>Enter the tempo:</p><input type="text" id="tempo" value="70"> 
    <p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn"> 
    <button onclick="begin()">Begin</button> 

JS ----

<script type="text/javascript"> 

    function Printer(){ 
     this.myString = document.getElementById("text").value; 
     this.myArray = this.myString.split(""); 
     this.tempo = document.getElementById("tempo").value; 
     this.len = this.myArray.length; 
     this.loop = function(){ 
      if(this.len > 0){ 
       document.getElementById("myTypingText").innerHTML += this.myArray.shift(); 
      } 

     } 
    } 

    function begin(){ 
     var test = new Printer(); 
     setInterval(test.loop,test.tempo); 
    } 

    </script> 

ответ

0

Вы должны использовать анонимную функцию в интервале, если вы хотите, чтобы функция loop будет выполняться в контексте объекта Printer. Также вам нужно каждый раз проверять длину массива, поскольку свойство len не будет обновляться при смещении массива.

function Printer() { 
    this.myString = document.getElementById("text").value; 
    this.myArray = this.myString.split(""); 
    this.tempo = document.getElementById("tempo").value; 
    this.loop = function() { 
     if (this.myArray.length > 0) { 
      document.getElementById("myTypingText").innerHTML += this.myArray.shift(); 
     } 

    } 
} 

function begin() { 
    var test = new Printer(); 
    setInterval(function() { 
     test.loop() 
    }, test.tempo); 
} 

См working fiddle

+0

так ... использовать функцию анонимной функции() {test.loop()}, то this.myArray может быть получен из принтера, не так ли? поэтому анонимная функция может запрашивать любые требуемые переменные даже внутри другой функции? –

0

Вот другой подход. Ваша основная проблема заключалась в использовании этого ключевого слова. Вы должны помнить, что при вводе другой области действия это ключевое слово изменяется. Здесь вы заметите, что я кэширую или сохраняю «это» так, чтобы использовать это новое значение «this» в этой функции. Plunker

<!DOCTYPE html> 
<html> 
    <head> 

    </head> 
    <body> 
<div id="myTypingText"></div> 
    <p>Enter the tempo:</p><input type="text" id="tempo" value="70"> 
    <p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn"> 
    <button onclick="begin()">Begin</button> 


<script type="text/javascript"> 

    function Printer(){ 
     this.myString = document.getElementById("text").value; 
     this.myArray = this.myString.split(""); 
     this.tempo = document.getElementById("tempo").value; 
     this.len = this.myArray.length; 
     var that = this; 
     this.loop = function(){ 
      if(that.myArray.length !== 0){ 
       document.getElementById("myTypingText").innerHTML += that.myArray.shift(); 
      } 

     } 
    } 

    function begin(){ 
     var test = new Printer(); 
     setInterval(test.loop,test.tempo); 
    } 

    </script> 
    </body> 
</html> 
Смежные вопросы