簡體   English   中英

如何在HTML中多次顯示JavaScript變量?

[英]How can I display a javascript variable multiple times in html?

我正在編寫一個文本游戲,該游戲會從數組中隨機生成許多變量,例如角色的名稱和他們的船名。 一旦運行了用於生成這些名稱的函數,我便在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和程序設計非常陌生,並且自己學習,因此請指出一些顯而易見的內容。

您不能兩次使用相同的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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM