我正在编写一个文本游戏,它可以从数组中随机生成许多变量,如角色的名称和他们船的名称。一旦产生这些名称的功能运行时,我用这样的事情在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