簡體   English   中英

如何用不在陣列中的項目替換陣列中的項目?

[英]How do I replace an item in an array with one that isn't in said array?

因此,我想將數組中的圖像之一更改為問號。 到目前為止,這就是我所擁有的。

var icons = new Array ();

    icons [0] = {   html: "Animals/Ape.png" };
    icons [1] = {   html: "Animals/Bat.png" };
    icons [2] = {   html: "Animals/Cow.png" };
    icons [3] = {   html: "Animals/Emu.png" };
    icons [4] = {   html: "Animals/Pig.png" };
    icons [5] = {   html: "Animals/Dog.png" };
    icons [6] = {   html: "Animals/Rat.png" };
    icons [7] = {   html: "Animals/Yak.png" };
    icons [8] = {   html: "Animals/Cat.png" };

function showBack()
    {
    document.getElementById('table').style.display = "none";
    document.getElementById('tableblank').style.display = "block";
    icons[0]="Animals/Q.png";

    setTimeout(showFront,3000);
    }

function showFront()
    {
    document.getElementById('table').style.display = "block";
    document.getElementById('tableblank').style.display = "none";
    document.getElementById('speech').style.display = "block";
    document.getElementById('typewindow').style.display = "block";

    }

我已經嘗試了幾種解決方案,但無法進行任何工作。 謝謝您的幫助 :)

如果您想重新分配該對象,可以這樣:

icons[0].html = "Animals/Q.png";

我會做這樣的事情...

var icons = [ "Animals/Ape.png", 
              "Animals/Bat.png",
              "Animals/Cow.png" ];

icons[1] = "Animals/Q.png";
document.write(icons[1]);

或者如果您想將網址保留為對象...

var oIcons = [{ html:"Animals/Ape.png" }, 
              {html:"Animals/Bat.png"}, 
              {html:"Animals/Cow.png"}];

oIcons[2].html = "Animals/Q.png";
document.write(oIcons[2].html);

所以基本上在秀場上你應該有...

 icons[0].html="Animals/Q.png";

考慮您在評論中發布的代碼:

<div id="containerGameplay">
    <div id = "table">
        <script>
            for (i = 0; i < 9 ; i++) {
                document.write ("<div class = 'tile'><img src='" + icons[i].html+ "'></div>");
            }
        </script>
    </div>

您正在頁面上運行內聯代碼,該代碼將在瀏覽器加載后立即執行。 要在以后更改圖像,您需要創建對要更改的元素的引用。 最簡單的方法是給您的元素ID,這將更改您的代碼,如下所示:

document.write("<div class='title'><img id='icon_" + i + "' src='" + icons[i].html+ "'></div>");

這將導致將第一張圖像( icon[0] )應用於ID為“ icon_0”的元素,以此類推。

以后,當您要更改圖像時,可以獲取對正確元素的引用,然后將src更改為該元素:

elem = document.getElementById('icon_0');
elem.src = "Animals/Q.png"; 

或者,按照我認為您最初嘗試做的事情,可以更改數組,然后設置新的源(src):

icons[0].html = "Animals/Q.png";
document.getElementById('icon_0').src = icons[0].html;

它們都是相同的,但是第二個示例也將值存儲在數組中。 請記住,沒有自動數據綁定,因此僅更改數組不會自動更新圖像元素。

暫無
暫無

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

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