2014-09-30 37 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