簡體   English   中英

Javascript無法從數組中獲取document.getElementById('cs')

[英]Javascript cant get document.getElementById('cs') from array

編輯:這是我的代碼當前的樣子。 它仍然無法正常工作。

<head>
<script>
window.onload = myload()
var ids[]
function myload() { 
      alert("hi")
      ids = [document.getElementById('bs'),
        document.getElementById('cs'),
        document.getElementById('ds')
      ]

    }

function border(){
    ids[1].style.border = "9px";
}
</script>
</head>
<body> //elements definded here </body>

我正在嘗試編寫一個以一定間隔更改圖像列表邊框的函數。 但是,我似乎無法使其工作。 我正在嘗試執行以下操作:

<head>
<script>
var ids = [document.getElementById('a'), 
           document.getElementById('b'), 
           document.getElementById('c')]

function(x){
    ids[x].border = "9px";
}
</script>
</head>
<body> //elements definded here </body>

但它沒有運行。 但是,當我運行時:

document.getElementById('a').border = "9px" 

它確實有效。 我猜我沒有從數組中正確調用它。 我究竟做錯了什么?

編輯:固定'a'在數組中兩次。

JavaScript中的數組從0開始索引,因此執行ids[0].style.border = "9px"; ids[2].style.border = "9px"; 將給您理想的效果。 您還需要訪問元素上的style屬性(我已在代碼中修復了該屬性)

在函數x出現之前回答原始問題

  1. [1]是b,因為JS數組從0開始
  2. 我希望有style.border。
  3. 該數組必須在對象渲染后定義。
    如果您在腳本標簽中具有ID為a,b,c的元素之前存在數組,那么您將獲得的id等於[undefined,undefined,undefined]

 window.onload = function() { // or addEventHandler OR put script before </body> var ids = [document.getElementById('a'), document.getElementById('b'), document.getElementById('a') ] ids[1].style.border = "9px solid black"; // the second element } 
 <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> 

使用功能:

 var ids=[]; // this is now global in scope function setIt(idx) { ids[idx].style.border = "9px solid black"; } window.onload = function() { // or addEventHandler OR put script before </body> ids = [document.getElementById('a'), document.getElementById('b'), document.getElementById('a') ] setIt(1); // the second element } 
 <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> 

修正程式碼

 window.onload = myload; // removed () var ids=[]; // missing an equals function myload() { alert("hi") ids = [document.getElementById('bs'), document.getElementById('cs'), document.getElementById('ds') ] border(); } function border() { ids[1].style.borderWidth = "9px"; // just setting border is not enough } 
 div { border: 1px solid red } 
 <div id="bs">A</div> <div id="cs">B</div> <div id="ds">C</div> 

暫無
暫無

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

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