2011-07-29 49 views
0
<html> 
<head> 
<script type="text/javascript"> 
var c=0; 
var t; 
var timer_is_on=0; 

function timedCount() 
{ 
document.getElementById('txt').value=c; 
if(c == 100) return; 
c=c+1; 
t=setTimeout("timedCount()",30); 
} 

function doTimer() 
{ 
if (!timer_is_on) 
    { 
    timer_is_on=1; 
    timedCount(); 
    } 
} 
</script> 
</head> 

<body onload="doTimer()"> 
<form> 
<input type="button" value="Start count!"> 
<input type="text" id="txt"> 
</form> 
<p>Click on the button above. The input field will count forever, starting at 0.</p> 
</body> 
</html> 

我想改變JavaScript的DOM問題

<input type="text" id="txt"> 

<div type="text" id="txt"> 

它不工作。 我認爲這個問題是

document.getElementById('txt').value=c; 

但我試過

document.getElementById('txt').innerHTML=c; 

它仍然無法正常工作。 有人能告訴我爲什麼嗎? 乾杯!

+0

這很奇怪,我試過喲你在http://jsfiddle.net/8fpht/的代碼,它的工作原理。什麼不工作?在哪個瀏覽器中?你可以在控制檯中看到javascript錯誤嗎? –

回答

2

設置文本框的值將填充在文本框中的文本。如果你想更換一個div輸入你應該使用:

element.replaceChild(newDiv, oldTextbox); 

嘗試:

var div = document.createElement("DIV"); 
div.id = "txt"; 
div.innerText = "Hello world!"; 

var tb = document.getElementById("txt"); 
tb.parentElement.replaceChild(div, tb); 
0

嘗試改變<div type="text" id="txt"><div id="txt">

+0

應該是一個評論。 – Pindatjuh

0

基本上,你問這樣做:

var d = document.createNode("div") 
d.setAttribute("id", "txt") 
d.setAttribute("type", "text"); 
var input = document.getElementById("txt"); 
input.parentElement.replaceChild(d, input); 

但我認爲你更好:

function timedCount() 
{ 
    document.getElementById('txt').value=c; 
    if(c == 100) return; 
    c=c+1; 
    t=setTimeout("timedCount()",30); 
} 

function doTimer() 
{ 
    if (!timer_is_on) 
    { 
     // set the input to readOnly, this allows JS to update it without 
     // letting the user modify the value. 
     document.getElementById('txt').readOnly = true 
     timer_is_on=1; 
     timedCount(); 
    } 
}