Uncaught TypeError: Cannot set property 'backgroundImage' of undefined althout js is called after page loads

Uncaught TypeError: Cannot set property 'backgroundImage' of undefined althout js is called after page loads

我认为通过在 </body> 之前使用 $(document).ready(function(){}) 页面将会加载,但是当我尝试通过 javascript 设置背景图片时,我得到:

Uncaught TypeError: Cannot set property 'backgroundImage' of undefined.

密码是:

<body>
<div class="bottom_header"></div>
<script>
  $(document).ready(function(){
  doSlideshow();

  function doSlideshow()
  {
     var x = document.getElementsByClassName("bottom_header");
     x.style.backgroundImage = "url('s1.jpg')";
  }
})
</script>
</body>

我也尝试了以下但结果相同typeError。我不明白我做错了什么。

<body>
<div class="bottom_header"></div>
<script>
window.onload = function() {
    alert("it's in");
    var x = document.getElementsByClassName("bottom_header");
    x.style.backgroundImage = "url('s1.jpg')";
}
</script>
</body>

document.getElementsByClassName returns 一个或多个元素,因此您需要获取第一个这样的元素(或遍历它们)。