2014-09-30 43 views
0

我正在編寫一個文本遊戲,它可以從數組中隨機生成許多變量,如角色的名稱和他們船的名稱。一旦產生這些名稱的功能運行時,我用這樣的事情在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和編程一般都很陌生,並且自己學習,所以請隨時指出一些看起來很明顯的東西。

+1

如果你要重複元素,你應該使用類而不是id。 ID是針對單個實例的。另外,請張貼一些HTML以更好地向我們展示您正在嘗試做的事情。 – disinfor 2014-09-30 15:56:56

回答

0

您不能兩次使用相同的ID。在JS中只考慮第一個,因爲它不需要額外的東西,在HTML中它違背標準,實際上是無效的HTML。

您需要可以使用不同的ID對每個元素,並通過你想要的ID作爲參數傳遞給函數:

var captainName = function (id) { 
    var e = firstName[Math.floor(Math.random() * firstName.length)] + " " + lastName[Math.floor(Math.random() * lastName.length)]; 
    document.getElementById(id).innerHTML = e; 
    e = captainName; // <-- also, what is this for? 
}; 

還是用類來代替,並在一次針對他們的所有:

var captainName = function() { 
    var e = firstName[Math.floor(Math.random() * firstName.length)] + " " + lastName[Math.floor(Math.random() * lastName.length)]; 
    // you can use forEach to iterate through them 
    document.getElementsByClassName("cap").forEach(function(el) 
     el.innerHTML = e; 
    }); 
    e = captainName; 
}; 
+0

非常感謝您的回覆。我是新來的,但使用類而不是id聽起來像我所需要的,如果這意味着我可以在描述html中多次引用變量(在這種情況下,船長和船的名稱)。 – kevinbraverman 2014-09-30 20:16:02