2012-10-24 51 views
2

我正在嘗試獲取多個元素,這些元素是根據3個數組「頂部」,「底部」,「鞋子」組織的。使用javascript更改多個圖像的樣式(不透明度)

我知道我可以使用

document.getElementsByClassName("class1 class2"); 

如何轉變作風爲每個對象的搶多個對象,我當前的代碼是:(我曾經嘗試都的知名度和透明度,但它不斷收到一個未捕獲的類型錯誤,因爲document.getelements ....不返回任何東西。

function filter() { 
var this_id = event.target.id; 
console.log(this_id); 
if (this_id = "filtertops") { 
    document.getElementsByClassName("a4 a7 a11 a12 a8").style.visibility="hidden"; //not tops 
    document.getElementsByClassName("a1 a2 a3 a5 a9 a10 a14").style.visbility="visible"; // tops 
    } 
else if (this_id = "filterbottoms") { 
    document.getElementsByClassName("a2 a3 a5 a10 a14 a8").style.opacity="0.4"; //not bottoms 
    document.getElementsByClassName("a1 a4 a7 a9 a11 a12").style.opacity="1"; //bottoms 
    } 
else if (this_id = "filtershoes") { 
    document.getElementsByClassName("a1 a2 a3 a4 a5 a7 a9 a10 a11 a12 14").style.opacity="0.4"; //not shoes 
    document.getElementsByClassName("a8").style.opacity="1"; //shoes 
    } 

我試圖將其分配給一個變量,以及再一個for循環來改變每個對象的樣式,但沒有工作。

function filterbottoms() { 
    var nonbottom = document.getElementsByClassName("a2 a3 a5 a10 a14 a8"); 
    var bottoms = document.getElementsByClassName("a1 a4 a7 a9 a11 a12"); 
    for (i in bottoms) 
     { 
      i.style.visibility='visible'; 
     } 
    for (i in nonbottom) 
     { 
      i.style.visibility='hidden'; 
     } 

} 
+0

CSS類名不得以數字開頭,請參閱:http://stackoverflow.com/questions/448981/what-c​​haracters-are-valid-in-css-class-names – feeela

回答

4

你是密切與for循環:

for (i in bottoms){ 
    bottoms[i].style.visibility='visible'; 
} 

應該<edit>但不會</edit>工作。每次迭代i是下一個密鑰,不是下一個

但應使用常規for而非for..in

for (var i = 0; i < bottoms.length; i++){ 
    bottoms[i].style.visibility='visible'; 
} 

編輯:我建議一個常規for循環,因爲使用for..in通常是不適合的陣列或陣列狀物體爲(取決於它會遍歷非數字屬性。約瑟夫的評論證實,在這種情況下,for..in絕對不會出於這個原因。

+0

實際上第一個將不起作用因爲...的語法。在遍歷nodeList對象時,它們有一個長度屬性,然後抱怨沒有style屬性。你提供的第二個應該工作。 –

+0

謝謝約瑟夫 - 答案更新了一點。 (很明顯,我建議使用傳統的for循環,因爲這樣的事情可能會發生,但我沒有仔細檢查它是否肯定會成爲NodeLists的問題。) – nnnnnn

+0

'document.getElementsByClassName(「class1 class2」); '返回'[]'。你知道這是爲什麼嗎? – Unistudent

相關問題