2011-11-02 50 views
0

这是我第二天用JavaScript做任何事情,所以我是一个完整的初学者。正如标题所述,我只是想使用settimeout函数更改文本框的文本值。我搜索了互联网,并走到了死胡同。这是我到目前为止,SetTimout函数改变文本框中的文本

putftp.onclick = function() { 
    var Text = document.getElementById("TextBox"); 


    function firsttext() { 
     document.getElementbyID("TextBox").innerHTML = "This is the first test."; 
     setTimeout("secondtest()",3000); 
    } 
    function secondtest() { 
     document.getElementById("TextBox").innerHTML = "This is the second test."; 
     setTimeout("thirdtest()",5000); 
    } 
    function thirdtest() { 
     document.getElementById("TextBox").innerHTML = "This is the last test."; 
    } 
}; 

林不知道,如果即时通讯使用正确的格式,或者,如果im甚至望其项背是正确。我非常确定除了document.getElementbyID(“textbox”)。innerHTML部分外,一切正常。我会认为有些事情会发生改变,但只是我的第二天,所以我完全可以对这个问题毫无头绪。感谢您的帮助!

+1

对于所有回答的人,'innerHTML'不会改变文本框的值> _>。它的'.value ='text'' – f0x

+0

@ f0x谢谢,注意到在构建测试用例时。 :) –

回答

3

到按钮点击后换一次3秒的文字,有这样的:

putftp.onclick = function() { 
    window.setTimeout(function() { 
     document.getElementById("TextBox").value = "This is the first test."; 
    }, 3000); 
}; 

你有,我为您解决您的一部开拓创新的代码中有两处错误:

  1. 假设TextBox是文本框中,您需要分配其value属性,而不是innerHTML
  2. 正确的名称是getElementById而不是getElementbyID。 JavaScript区分大小写。

两秒钟后再次进行更改,您可以添加 “嵌套” 定时器:

putftp.onclick = function() { 
    window.setTimeout(function() { 
     document.getElementById("TextBox").value = "This is the first test."; 
     window.setTimeout(function() { 
      document.getElementById("TextBox").value= "This is the second test."; 
     }, 2000); 
    }, 3000); 
}; 

Live test case

+0

+1:强烈赞成这种做法。 –

+0

感谢修正阴影! – javasocute

+0

当然,这就是我们在这里。 :-) –

1

函数在执行时未定义,因为传递字符串会导致它在全局范围内运行。这些函数仅在onclick处理程序中定义。

您应该只传递函数本身,并且不要传递字符串。另外,为什么不实际使用Text变量?你应该通过执行第一个函数来启动这个过程。

请注意,您的texttest的命名不是很好;它很容易被误读。

putftp.onclick = function() { 
    var Text = document.getElementById("TextBox"); 

    firsttext(); // start process 

    function firsttext() { 
     Text.innerHTML = "This is the first test."; 
     setTimeout(secondtest, 3000); 
    } 

    function secondtest() { 
     Text.innerHTML = "This is the second test."; 
     setTimeout(thirdtest, 5000); 
    } 

    function thirdtest() { 
     Text.innerHTML = "This is the last test."; 
    } 
}; 
2

您发布的代码的明显问题是您没有调用firsttest()-功能。因此,第一次调用setTimeout永远不会被创建。此外,你可以通过自己传递函数来增强你的脚本,像这样:setTimeout(secondtest, 3000);

其次,既然你已经获得了一次元素,为什么不缩短代码通过削减一些getElementById:s出来。

putftp.onclick = function() { 
    var Text = document.getElementById("TextBox"); 

    function firsttext() { 
     Text.innerHTML = "This is the first test."; 
     setTimeout(secondtest, 3000); 
    } 
    function secondtest() { 
     Text.innerHTML = "This is the second test."; 
     setTimeout(thirdtest, 5000); 
    } 
    function thirdtest() { 
     Text.innerHTML = "This is the last test."; 
    } 

    firsttext(); 
}; 
+0

是的这种方法也应该工作。 –

+0

+1更多的教我叫第一个功能。谢啦 – javasocute