Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按类名获取元素不起作用_Javascript_Function_Onload_Classname - Fatal编程技术网

Javascript 按类名获取元素不起作用

Javascript 按类名获取元素不起作用,javascript,function,onload,classname,Javascript,Function,Onload,Classname,对不起,如果我是一个noob,但这行代码将不会为我工作的某些原因,它看起来是正确的 $(window).load(function() { document.getElementByClassName("example").style.width = "50%"; setTimeout(function () { document.getElementByClassName("example").style.width = "50%"; }, 3000);

对不起,如果我是一个noob,但这行代码将不会为我工作的某些原因,它看起来是正确的

$(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
此外,它还将生成一个
节点列表
,因此我们必须对其进行迭代,为其设置
属性

 var elems = document.getElementsByClassName("example");
 for(var i=0;i<elems.length;i++){
   elems[i].style.width = "50%";
 }
上面的代码将
节点列表
转换为
数组

您拥有
$(窗口)
,这意味着您正在尝试使用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);
});  

将为您提供正确的结果。

非常感谢您,您是正确的谢谢您!我会在6分钟后给你答案passes@brigitte18如果答案是你想要的,请接受
$(window).load(function() 
{
    document.getElementsByClassName("example").style.width = "50%";

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