所以这是我的代码
function listview() {
//li list//
var li = document.getElementById("sortcontainer").
getElementsByClassName("game");
for(var i = 0; i < li.length; i) {
li[i].className = "lilistview";
}
//li image list//
var img = document.getElementById("sortcontainer").
getElementsByClassName("image");
for(var j = 0; j < img.length; j) {
img[j].className = "imglistview";
}
//header list//
var header1 = document.getElementById("sortcontainer").
getElementsByClassName("title");
var header2 = document.getElementById("sortcontainer").
getElementsByClassName("date");
var header3 = document.getElementById("sortcontainer").
getElementsByClassName("thumbrating");
for(var k = 0; k < header1.length; k) {
header1[k].className = "listviewchildren";
}
for(var l = 0; l < header2.length; l) {
header2[l].className = "listviewchildren";
}
for(var m = 0; m < header3.length; m) {
header3[m].className = "listviewchildren";
}
}
它一遍又一遍地使用相同的代码将缩略图视图更改为列表视图,但代码看起来很长,而且从两者变化很慢。
有什么建议吗?
答案 0 :(得分:1)
window.onload = function() {
var sortcontainer = document.getElementById("sortcontainer"); // used many times
listview();
}
function listview() {
changeClass("game", "lilistview");
changeClass("image", "imglistview");
changeClass("title", "listviewchildren");
changeClass("date", "listviewchildren");
changeClass("thumbrating", "listviewchildren");
}
function changeClass(oldClassName, newClassName) {
var elementsByClass = sortcontainer.getElementsByClassName(oldClassName);
console.log("-- " + oldClassName + " -- " + newClassName + " --");
console.log("changing " + elementsByClass.length + " classnames");
for (i=0; i<elementsByClass.length; i+=1) {
elementsByClass[i].className = newClassName); }
}