2011-11-02 33 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