2011-10-14 40 views
0

好吧,我需要做的是在鍵盤按下時改變屏幕上的一些數字,我有它的工作,但我不滿意。更優雅的方式來改變我的div的價值?

我有一個輸入字段和一個div,當輸入字段的值更改時正在更新。我這樣做是爲了不受輸入字段閃爍的克拉等的限制。我不想顯示輸入字段,但是當我用CSS隱藏或輸入=「hidden」時,它不再有效。我試圖得到這與JS變量的工作,但迄今爲止不成功。

任何想法?

HTML

<html> 
<head> 
<link rel="stylesheet" type="text/css" href="number.css" /> 
</head> 

<body onLoad="focus();myText.focus();changeNumber()"> 

<div id='number'> 

</div> 

<input type="text" id="myText" value="1"/> 

</body> 

<footer> 
<script type="text/javascript" src="number.js"></script> 
</footer> 

</html> 

JAVASCRIPT

var myText = document.getElementById("myText"); 

function changeNumber(){ 
var userInput = document.getElementById('myText').value; 
document.getElementById('number').innerHTML = userInput; 
} 

// Capture keyDown events 
myText.onkeydown = function(e) { 
// "34" is the up arrow key 
if (e.keyCode == 34) { 
    // increment the value in the text input 
    myText.value++; 
changeNumber() 

// "33" is the down arrow key 
} else if (e.keyCode == 33 && myText.value > 1) { 
    // decrement the value in the text input 
    myText.value--; 
changeNumber() 
} 
} 

在這裏,在最後的固定編碼*謝謝你們! **

HTML

<html> 
<head> 
<link rel="stylesheet" type="text/css" href="number.css" /> 
</head> 

<body onLoad="focus();number.focus();changeNumber()"> 

<div id='number' value="1"> 

</div> 

</body> 

<footer> 
<script type="text/javascript" src="number.js"></script> 
</footer> 

</html> 

JAVASCRIPT

var i = parseInt(1); 

function changeNumber(){ 
var userInput = i; 
document.getElementById('number').innerHTML = userInput; 
} 

// Capture keyDown events for document 
document.onkeydown = function(e) { 
// "34" is the PGUp key 
if (e.keyCode == 34) { 
    // increment the value in the text input 
    (i++); 
changeNumber() 

// "33" is the PGDown key 
} else if (e.keyCode == 33 && i > 1) { 
    // decrement the value in the text input 
    (i--); 
changeNumber() 
} 

// "66" is the b key 
if (e.keyCode == 66){ 
window.location.reload() 
} 

} 

回答

0

與您的代碼的問題是這樣的:

myText.value--; 

myText.value++; 

myText是DOM元素,而value酒店有一個字符串,而不是一個整數,我建議你這樣做:

var i = parseInt(myText.value); 
myText.value = (i++); 
+0

我會看看有什麼我可以用這個做的,這是有道理的,我不是很好的JavaScript我通常在客觀的C/iPhone程序。 :( – KDM

+0

得到它的工作見上文! – KDM