【问题标题】:Get element by classname not working按类名获取元素不起作用
【发布时间】:2016-06-18 14:28:05
【问题描述】:

对不起,如果我是菜鸟,但这行代码对我不起作用,因为它看起来正确。

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

【问题讨论】:

    标签: javascript function onload classname


    【解决方案1】:

    正确的函数名是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

    【讨论】:

    • 非常感谢,您说得对,谢谢谢谢!超过6分钟后我会给你答案
    • @brigitte18 如果这是您要找的,请接受答案
    【解决方案2】:

    getElementsByClassName 是复数。与寻找身份证相反,您通常会得到多个答案。所以把你的代码改成:

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

    将为您提供正确的结果。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 2020-10-30
        • 2021-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多