[英]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出現之前回答原始問題
[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.