按类名获取元素不起作用

Get element by classname not working

抱歉,如果我是菜鸟,但由于某些原因它看起来正确,这行代码对我不起作用。

$(window).load(function()  {
    document.getElementByClassName("example").style.width = "50%";
    setTimeout(function () {
       document.getElementByClassName("example").style.width = "50%";
    }, 3000); 
});  

正确的函数名是getElementsByClassName,注意复数形式。

document.getElementsByClassName("example")[0].style.width = "50%";
//Just an example for how to set the property for the first element
//we have to iterate over that collection and set property one by one

它也会产生一个 node list,所以我们必须迭代它来为它设置 properties

 var elems = document.getElementsByClassName("example");
 for(var i=0;i<elems.length;i++){
   elems[i].style.width = "50%";
 }

另请注意 node list 不是 array。它是一个类似对象的数组。人们通常将它们视为数组,他们会尝试在其上使用数组函数。这将导致错误。如果你想把它转换成一个数组,那么EC6中有一个方便的函数,我们可以使用它。

 var arr = Array.from(document.getElementsByClassName("example"));

以上代码会将 node list 转换为 array

您有 $(window),这意味着您正在尝试使用 jQuery。如果您尝试使用 jQuery,请确保它包含在您的页面中。另外写成下面的方式会更容易

$(window).load(function() 
{
$(".example").css('width',"50%");

setTimeout(function () {
  $(".example").css('width', "50%");
}, 3000); 

});  

getElementsByClassName 是复数。与寻找 ID 相比,您通常会得到不止一个答案。因此,将您的代码更改为:

$(window).load(function() 
{
    document.getElementsByClassName("example").style.width = "50%";

    setTimeout(function () {
        document.getElementsByClassName("example").style.width = "50%";
    }, 3000);
});  

会给你正确的结果。