关于树节点巨多时获取用户选中(可多选)节点的优化

前端开发时,单从性能上考虑,对dom的遍历越少性能越好,最好是能不去遍历dom树;下面事例中用户可以多选,一个没有保存用户选中的项,一个保存了用户选中的项,下面看实例代码:

html:

<ul>
  <li>
    <ul>
      <li>
        ...
      </li>
    </ul>
  </li>
</ul>

 优化前的javascript:

jQuery("body").on("click","li",function(){
  currentItem= jQuery(this);
    // 用户可以取消选中状态
    currentItem.toggleClass("selected");
});                

优化后javascript:

var self = {guid:1,selectedFile:{}};
jQuery("body").on("click","li",function(){
  currentItem= jQuery(this);
  // 给每个文件一个唯一的id
  if(!currentItem.data("id")){
    currentItem.data("id",self.guid++);
  }
  // 用户可以取消选中状态
  currentItem.toggleClass("selected");
  if(currentItem.hasClass("selected")){
     // 选中文件保存到选中对象列表中
     self.selectedFile[currentItem.data("id")] = currentItem;
  }
  else{
     // 否则从选中对象列表中删除
     delete self.selectedFile[currentItem.data("id")];
  } 
});            

说明:看起来优化后的代码多了,但是如果html嵌套的dom节点很多的话(比如一个企业的联系人树形结构,可能有上万个),要获取用户已经选中的项时,那么优化后的javascript的性能将充分体现出来,优化前只能通过jQuery("li.selected")获取到用户选中项(意味着javascript要在浩瀚的联系人树中查找),但优化后的代码只需要通过self.selectedFile即可获取选中项,根本就不用去遍历dom树。如果是单选的话就不需要guid了,从而不需要给元素加guid,这样代码会少很多,但原理是一样的。

原文地址:https://www.cnblogs.com/cqiliang/p/3120097.html