我正在編寫一個文本遊戲,它可以從數組中隨機生成許多變量,如角色的名稱和他們船的名稱。一旦產生這些名稱的功能運行時,我用這樣的事情在HTML的身體:如何在html中多次顯示javascript變量?
<pre> The sea welcomes you back. It is finally time to achieve your destiny. Become who you were born to be.
You are <ins class="cap"></ins>, Captain of <ins id="ship"></ins>, <a id="story"></a>, and there is nothing standing between you, and fame, and fortune.
Your fearsome crew has been assembled. <ins id="crew1"></ins> is your first mate, <ins id="crew2"></ins> and <ins id="crew3"></ins> man the deck, and <ins id="crew4"></ins> is up in the crow's nest. They are a raggedy bunch but they'll see you through if the gold is right.
<a id="crew1"></a> glances back at the helm, ready to draw the anchor and set sail. You give the command and <ins id="ship"></ins> sets off into a bright, cloudless morning...</pre>
那裏有在JavaScript這些功能,以填補那些:
var captainName = function() {
var e = firstName[Math.floor(Math.random() * firstName.length)] + " " + lastName[Math.floor(Math.random() * lastName.length)];
document.getElementById("cap").innerHTML = e;
e = captainName;
};
var ship = function() {
var e = shipName[Math.floor(Math.random() * shipName.length)];
document.getElementById("ship").innerHTML = e;
e = shipName;
};
captainName();
ship();
和它會顯示像這樣:
你是Django de Bois,黑色之美隊長。
但是,當我想再次顯示字符的名稱,並且我在html中使用另一個標記時,它仍然是空的。我認爲它不希望重複的標籤具有相同的標識,但我無法確定。我對JavaScript和編程一般都很陌生,並且自己學習,所以請隨時指出一些看起來很明顯的東西。
如果你要重複元素,你應該使用類而不是id。 ID是針對單個實例的。另外,請張貼一些HTML以更好地向我們展示您正在嘗試做的事情。 – disinfor 2014-09-30 15:56:56