简体   繁体   English

javascript加载缓慢,代码似乎很大?

[英]Slow javascript loading, code seems very big?

So here is my code 所以这是我的代码

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";
   }

}  

It bassically uses the same code over and over again to change a thumbnail view to a list view but the code seems so long, and is slow to change from the two. 它一遍又一遍地反复使用相同的代码将缩略图视图更改为列表视图,但是该代码看起来很长,并且从这两个代码更改起来很慢。

Any suggestions? 有什么建议么?

EDIT: I redid the whole thing after thinking about it overnight. 编辑:经过一整夜的思考,我重做了整个事情。
1) This is more for my benefit than yours. 1)这对我的好处比对您的好处更多。
2) You are changing ClassNames, right? 2)您正在更改ClassName,对吗?
3) Get var sortcontainer = .. once instead of 5 times. 3)一次获得var sortcontainer = ..而不是5次。
4) The "for (var i=0; i<li.length; i) { .." will loop unless li.length is zero. 4)除非li.length为零,否则“ for(var i = 0; i <li.length; i){..”将循环。
5) One routine will handle all 5 sets of elements. 5)一个例程将处理所有5组元素。
6) The page has to be loaded. 6)必须加载页面。

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); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM