2015-12-01 20 views
2

我想將JavaScript函數的結果打印到HTML/PHP頁面中的表格中。我嘗試使用「document.write(player1Name);」 但它沒有奏效。 因此,當我輸入的東西在文本框中 text fields將某些東西從JavaScript打印到HTML/PHP頁面中的表格

我想在這個表table

這是打印的結果是我的劊子手主頁代碼:

<form id="Player1" class="Player1"> 
     <input type="text" id="playerOneName"/> 
    </form> 
    <form id="Player2" class="Player2"> 
     <input type="text" id="playerTwoName"/> 
    </form> 
    <button id="Enter" class="Enter" type="button" onclick="navigateToDifficultyForMultiPlayer()"> 
     <a>Enter</a> 
    </button> 

這是在我的多玩家頁面代碼表中:

<TABLE BORDER="5" WIDTH="20%" CELLPADDING="5" CELLSPACING="2" id="Score-Board"> 
    <TR> 
     <caption id="table-title">Score Board</caption> 
     </TH> 
    </TR> 
    <TR ALIGN="CENTER"> 
     <TH colspan="2"> <script> document.write(player1Name);</script> </TH> 
     <TH colspan="2"><script> var player2Name </script></TH> 
    </TR> 
    <TR ALIGN="CENTER"> 
     <TH colspan="2">score</TH> 
     <TH colspan="2">score</TH> 
    </TR> 
</TABLE> 

這是我的Java Script代碼,我創建做我想做的事情(我覺得我已經做了右):

function navigateToDifficultyForMultiPlayer() { 
    //set player names in session 
    setPlayerNames(); 
    //navigate to DifficultyForMultiPlayer page 
    location.href = "DifficultyForMultiPlayer.html"; 
} 

function setPlayerNames() { 
    var firstPlayerName = document.getElementById("playerOneName").value; 
    var secondPlayerName = document.getElementById("playerTwoName").value; 
    console.log(firstPlayerName + " " + secondPlayerName); 
    sessionStorage.setItem("Player1Name", firstPlayerName); 
    sessionStorage.setItem("Player2Name", secondPlayerName); 
} 
function getPlayerNames(){ 
    player1Name = sessionStorage.getItem("Player1Name"); 
    player2Name = sessionStorage.getItem("Player2Name"); 
    console.log(player1Name + " " + player2Name); 
} 

這是多數民衆贊成在全球範圍調用的JavaScript:我希望每個人都能

var player1Name; 
var player2Name; 

瞭解我想問的問題。請不要猶豫,告訴我我的問題是否有問題。我盡力妥善問的問題,僅供參考英語不是我的第一語言

+0

如果我們的答案有幫助,請記得接受它們。謝謝。 – Cruiser

回答

1

你想要做的就是在這個網站:

<TR ALIGN="CENTER"> 
    <TH colspan="2"> <script> document.write(player1Name);</script> </TH> 
    <TH colspan="2"><script> var player2Name </script></TH> 
</TR> 

的ID添加到您的個元素:

<TH colspan="2" id="player1"> // and remove the script 

然後,在你的javascript,可能在你的getPlayerNames功能:

document.getElementById("player1").text(player1Name); 

然後在S ame for player2。

1

你可以給你的<th>標籤給像player1player2這樣的玩家id。然後,在你的<body>對於多種播放頁面的最後,你可以把一個<script>標記,確實是這樣的:

<script> 
(function() { 
    document.getElementById("player1").innerHTML = player1Name; 
    document.getElementById("player2").innerHTML = player2Name; 
})(); 
</script> 

的的document.getElementById抓住你想要然後.innerHTML變化是什麼範圍內的DOM元素該標籤。在body標籤結束之前放置它會確保在嘗試訪問它們之前首先加載html元素。

相關問題