2014-01-06 61 views
2

我正在嘗試使用文本輸入和提交按鈕創建日誌框。我可以得到它顯示輸入的文字與帶文本輸入的日誌框

var test = function() { 
var test1 = document.getElementById('input'); 
var totalTest = test1.value; 
document.getElementById('log').innerHTML += totalTest; 
}; 

但我不能得到它來回應它。我想繼續提問,所有答案都來自一個輸入框。我對JavaScript仍然很陌生,並且會愛任何人的幫助。 這是我迄今爲止所有。 JAVASCRIPT:

var playerInput = function() { 
var pInput = document.getElementById('input'); 
var input = pInput.value; 
}; 

var playerNum = function() { //Choice between Single and Multiplayer 
    document.getElementById('log').innerHTML = "Would you like to play singleplayer or multiplayer?"; 
oneOrTwo(input); 
}; 

var oneOrTwo = function (input) { 
    var playerAmount = input; 
    if (playerAmount == "singleplayer") { 
     //singlePlay(); 
    } else { 
     document.getElementById('log').innerHTML = "Multiplayer is coming soon"; 
     //multiPlay(); 
    } 
}; 

HTML:您輸入變量的

<!DOCTYPE html> 
<html> 
    <head> 
     <title> Rock Paper Scissors, with Single and Multiplayer! </title> 
     <link rel='stylesheet' href='style.css'/> 
    <script src='script.js'></script> 
</head> 
<body> 
    <div id="logHeader"> 
     <h1 style="font-size: 20px; font-family: calibri;"> Rock, Paper, Scissors </h1> 
    </div> 
    <div id="log"></div> 
    <br > 
    <input id="input" type="text" onFocus="if(this.value=='Type here') this.value='';" style="border: 2px solid; width: 300px; background-color: lightblue;" value="Type here"> 
    <input type="button" value="Enter" onClick="test()"> 
    <br > 
    <br > 
    <input type="button" onclick="playerNum()" value="Start Game"> 

</body> 
</html> 

回答

1

真的需要改變的是將oneOrTwo(input)調用移動到playerInput()函數。

提問後立即嘗試閱讀輸入信息是沒有意義的;用戶將沒有時間迴應。

var playerNum = function() { //Choice between Single and Multiplayer 
    document.getElementById('log').innerHTML = "Would you like to play singleplayer or multiplayer?"; 
    //nothing else, read the input later 
}; 

當玩家進入一個響應,並點擊 '確認' 按鈕,然後嘗試讀取輸入:

var playerInput = function() { 
    var pInput = document.getElementById('input'); 
    var input = pInput.value; 
    oneOrTwo(input); 
}; 

以及相應的HTML:

<input type="button" value="Enter" onClick="playerInput()"> 

投擲了它變成一個JSFiddle在這裏:http://jsfiddle.net/KfUp8/

1

var input = pInput.value;存儲值。

除非再次執行同一行,否則它不會改變。

oneOrTwo(input);替換爲oneOrTwo(pInput.value);以獲得每次新鮮的價值。

+0

這應該工作,但現在米Ÿ問題是我需要運行'oneOrTwo(pInput.value);'在我按下輸入按鈕後。 – Gateway12231

+0

@ Gateway12231你已經是。按提交按鈕運行調用'oneOrTwo'的'playerNum'。只需用'pInput.value'替換'input',每次按下按鈕都會起作用。 – rockerest