如何在html中多次显示javascript变量?

时间:2014-09-30 15:49:42

标签: javascript html variables

我正在编写一个文本游戏,它可以从数组中随机生成许多变量,比如角色的名称和船名。一旦运行了生成这些名称的函数,我就在html的主体中使用这样的东西:

<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中使用另一个标记时,它仍然是空的。我认为它不希望重复的标签具有相同的ID,但我无法确定。我对javascript和编程非常陌生并且自己学习,所以请随意指出可能看得很明显的东西。

1 个答案:

答案 0 :(得分: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;
};