可以��过以下几种方式来优化这段代码:

  1. 使用事件委托:将li和span的点击事件绑定到它们的父元素上,减少事件监听器的数量。

  2. 使用文档片段:将创建的li和div元素先添加到文档片段中,然后再一次性地添加到DOM中,可以减少对DOM的多次操作,提高性能。

  3. 使用缓存变量:将频繁使用的DOM查询结果和数据存储在变量中,避免重复查询和访问。

  4. 使用模板字符串:使用模板字符串来创建HTML元素,可以使代码更简洁、易读。

下面是优化后的代码示例:

const optionContainer = document.querySelector(".option");
const listContainer = document.querySelector(".list");

const fragment = document.createDocumentFragment();

for (const item of KeywordFiltering) {
  const li = document.createElement("li");
  li.innerText = item.name;
  
  const div = document.createElement("div");
  div.className = item.class;
  
  fragment.appendChild(li);
  fragment.appendChild(div);
  
  li.addEventListener("click", () => {
    const allDivs = document.querySelectorAll(".list div");
    allDivs.forEach(allDiv => {
      allDiv.style.display = "none";
    });
    
    div.style.display = "block";
    optionContainer.style.display = "none";
    
    document.querySelector(".confirm").onclick = () => {
      if (item.data.includes(userValue.value)) {
        alert("已存在");
        return;
      }
      
      const span = document.createElement("span");
      span.innerText = userValue.value;
      div.appendChild(span);
      item.data.push(userValue.value);
      
      span.addEventListener("click", () => {
        span.remove();
        item.data = item.data.filter(item => item !== span.innerText);
        console.log(span, item.data);
      });
      
      console.log(item.data, userValue.value);
    };
  });
  
  item.data.forEach(subitem => {
    const span = document.createElement("span");
    span.innerText = subitem;
    div.appendChild(span);
    
    span.addEventListener("click", () => {
      span.remove();
      item.data = item.data.filter(item => item !== subitem);
      console.log(span, item.data);
    });
  });
}

optionContainer.appendChild(fragment);
listContainer.appendChild(fragment);

请注意,上述代码仅提供了一种优化方案,具体的优化方式可能还需要根据实际情况进行调整

for const item of KeywordFiltering let li = documentcreateElementli liinnerText = itemname documentquerySelectoroptionappendChildli let div = documentcreateElementdiv divclassName = it

原文地址: https://www.cveoy.top/t/topic/ilWR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录