函数将字符串变量的子字符串按字符键入文本框

时间:2015-12-21 17:56:27

标签: javascript

所以,当我没有传递任何参数时它正在工作,并且在函数中我给它一个特定的变量来输入。无论如何,我希望函数具有灵活性,并且可以使用我称之为的任何变量。

var msg = "some text";

function writer(x) {
    setTimeout(function () { 
    text.textContent = x.substring(0, i);
    i++;
        if (i <= 60) {
            writer();
            } 
    }, 20)

};  

writer(msg);

也不工作。

i=0;

var msg = "some text";

function writer() {
    setTimeout(function (x) { 
    text.textContent = x.substring(0, i);
    i++;
        if (i <= 60) {
            writer();
            } 
    }, 20)

};  

writer(msg);

GOT IT!

i=0;

var msg = "some text";

function writer(x) {
    setTimeout(function () { 
    text.textContent = x.substring(0, i);
    i++;
        if (i <= 60) {
            writer(x);
            } 
    }, 20)

};  

writer(msg);

1 个答案:

答案 0 :(得分:0)

您遇到的问题是您没有将文本传递给方法。您需要在超时内传递消息。其他解决方案是不传递消息并仅使用全局变量。

&#13;
&#13;
var msg = "some text",
    i = 0,
    text = document.getElementById("out1");

function writer (x) {  
    setTimeout(function () { 
        text.textContent = x.substring(0, i);  //or change x to msg and do not worry about passing in the string
        i++;
        if (i <= x.length) {  //base off length, not a random number
            writer(x);  //or get rid of x
        } 
    }, 20);
};  

writer(msg);  
&#13;
<div id="out1"></div>
&#13;
&#13;
&#13;

您的代码的另一个问题是您依赖全局变量(它们可能与本地不同),因此您无法在没有冲突的情况下多次运行代码。因此,更好的想法是将递归封装在方法内部并调用它,以便您可以维护每个实例的状态。

基本理念:

&#13;
&#13;
function writer(element, message, speed) {
  
    var currentStep = 0;  //holds where we are in the text animation
    speed = speed || 200; //If no value given, set to a default
    function step() {  // a local function that will hold the state of the variables so we do not have to pass anything around
        element.textContent = message.substr(0, currentStep++);  //set the text and update the step we are on    
        if (currentStep<=message.length) {  //Check to see if we still have more characters to dislay
            setTimeout(step, speed);  //if we do, set the timeout
        }
    }
  
    step();  //init the animation

};  

//Examples calling it
writer(document.getElementById("out1"), "Hello World! How are you doing today?" );
writer(document.getElementById("out2"), "Hello World! How are you?", 400 );
&#13;
<div id="out1"></div>
<div id="out2"></div>
&#13;
&#13;
&#13;