2016-03-04 47 views
1

對不起,如果我是一個noob,但這行代碼不會爲我工作的某種原因,它看起來是正確的。通過類名不工作獲取元素

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

回答

4

正確的函數名是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 listarray

+2

非常感謝你,你是正確的謝謝你謝謝你!我會在6分鐘限制通過後給你答案 – brigitte18

+0

@ brigitte18請接受答案,如果它是你正在尋找的 –

1

你有$(window)這意味着你正在嘗試利用jQuery。如果您嘗試使用jQuery,請確保它包含在您的頁面中。以下列方式編寫會更容易:

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

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

}); 
-2

getElementsByClassName是複數。反對尋找身份證的人通常會得到不止一個答案。因此,將您的代碼更改爲:

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

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

將爲您提供正確的結果。

+2

解決方案是....? – CMedina