编辑:这是我的代码当前的样子。它仍然无法正常工作。

<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'在数组中两次。

最佳答案

在函数x出现之前回答原始问题


[1]是b,因为JS数组从0开始
我希望有style.border。
该数组必须在对象渲染后定义。
如果您在具有id的元素之前的script标记中包含数组
a,b,c存在,那么您将获得等于
[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>

关于javascript - Javascript无法从数组获取document.getElementById('cs'),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52559976/

10-12 14:20
查看更多