2017-03-02 187 views
-1

我有3個DivID作爲「襯衫」,「帽衫」,「其他」 然後我有一個JavaScript函數。我如何能夠爲這三個ID使用相同的Js功能?一個JavaScript函數爲多個div ID

function myAccFunc() { 
    var x = document.getElementById("divID"); 
    if (x.className.indexOf("w3-show") == -1) { 
    x.className += " w3-show"; 
    } else { 
    x.className = x.className.replace(" w3-show", ""); 
    } 
}  
+3

把所有的IDS在一個數組和循環他們,通過ID作爲你的函數PARAM並使用它。 –

+3

你可以給所有的div一個共同的類,並改變你的功能從id到類的參考 –

+1

@LelioFaieta鍵盤滴 – axelduch

回答

0

調用函數如下:

myAccFunc("shirts"); 
myAccFunc("hoodies"); 
myAccFunc("other"); 

和這樣的功能:

function myAccFunc(div){ 
    var x = document.getElementById(div); 
    if (x.className.indexOf("w3-show") == -1){ 
     x.className += " w3-show"; 
    }else{ 
     x.className = x.className.replace(" w3-show", ""); 
    } 
} 
+0

我知道這是簡單的。謝謝! – blackmist1337

1
function myAccFunc(id){ 
    var x = document.getElementById(id); 
    if(!x) return; 

    if (x.className.indexOf("w3-show") == -1) 
    x.className += " w3-show"; 
    else 
    x.className = x.className.replace(" w3-show", ""); 
} 


['id1', 'id2', 'id3'].forEach(myAccFunc); 

你可能有興趣使用classList(ES2015)。除了舊的IE以外,它的支持情況非常好。

0

嘗試向想要編輯的div添加另一個類,然後調用它。另外,爲什麼使用indexOf檢查是否存在時,你可以使用includes

var x = document.getElementsByClass('checkClass'); 
for (i=0;i<x.length - 1;i++){ 
    if (!x[i].className.includes("w3-show")){ 
     x[i]className += " w3-show"; 
    } else { 
    x[i].className = x.className.replace(" w3- show", ""); 
    } 
} 
-2

我假設你不想在默認情況下顯示所有這些

你可以通過div_id作爲PARAM然後使用事件偵聽器爲每個div調用函數。

func myAccFunc(div_id){ 
    var x = document.getElementById(div_id); 
    // rest of your code here 
} 

// event listeners 
document.getElementById("show_shirts_btn").addEventListener("click", function(){ 
     myAccFunc(shirts) 
    }); 

document.getElementById("show_hoodies_btn").addEventListener("click", function(){ 
     myAccFunc(hoodies) 
    }); 


document.getElementById("show_other_btn").addEventListener("click", function(){ 
     myAccFunc(other) 
    }); 
相關問題