一个用于多个div id的Javascript函数
我有3个部门ID,分别是“衬衫”、“连帽衫”、“其他” 然后我有一个JavaScript函数。我怎样才能对所有3个ID使用相同的Js函数一个用于多个div id的Javascript函数,javascript,html,function,Javascript,Html,Function,我有3个部门ID,分别是“衬衫”、“连帽衫”、“其他” 然后我有一个JavaScript函数。我怎样才能对所有3个ID使用相同的Js函数 function myAccFunc() { var x = document.getElementById("divID"); if (x.className.indexOf("w3-show") == -1) { x.className += " w3-show"; } else { x.className = x.classN
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", "");
}
}
您可能对使用(ES2015)感兴趣。除了旧的IE之外,它的支持非常好。尝试将另一个类添加到要编辑的div中,然后调用它。另外,当您可以使用
包含时,为什么要使用索引of
来检查是否存在
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", "");
}
}
var x=document.getElementsByClass('checkClass');
对于(i=0;i我假设您不希望在默认情况下显示所有属性
您可以将div_id作为参数传递,然后使用事件侦听器为每个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)
});
调用此函数:
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", "");
}
}
将所有id放在一个数组中并循环它们,将id作为函数参数传递并使用它。您可以给所有div一个公共类,并将函数中的引用从id更改为class@LelioFaieta键盘drop@axelduch谢谢你的注意:)我知道这很简单。非常感谢。
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", "");
}
}