优化的方法有以下几点:

  1. 减少不必要的DOM操作:在循环中,多次使用querySelector和querySelectorAll方法会带来性能问题。可以将这些操作提到循环外部,或者使用类似于缓存的方式,将查询结果保存起来,避免重复查询。

  2. 使用事件委托:可以将li元素的点击事件委托给父元素,这样可以避免为每个li元素都绑定一个事件监听器,提高性能。

  3. 避免频繁的重绘和回流:通过将需要频繁操作的元素隐藏起来,只在需要的时候再显示出来,可以减少重绘和回流的次数,提高性能。

  4. 使用数组的高阶方法:可以使用数组的高阶方法(如map、filter、reduce等)来简化代码逻辑,提高可读性和维护性。

下面是根据以上优化方法对代码进行修改的示例:

let userValue = document.querySelector(".content")
let KeywordFiltering = [
  { name: "名字", class: "username", data: ["嘻嘻", "哈哈", "嘿嘿"] },
  { name: "文案", class: "Copywriting", data: [4, 5, 6] },
  { name: "全选", class: "selectall", data: [7, 8, 9] }
]

const optionList = document.querySelector(".option");
const listDivs = document.querySelectorAll(".list div");

KeywordFiltering.forEach(item => {
  let li = document.createElement("li")
  li.innerText = item.name
  optionList.appendChild(li)
  let div = document.createElement("div")
  div.className = item.class
  document.querySelector(".list").appendChild(div)

  li.onclick = () => {
    listDivs.forEach(allDiv => allDiv.style.display = "none");
    div.style.display = "block";
    optionList.style.display = "none";

    document.querySelector(".confirm").onclick = () => {
      if (item.data.includes(userValue.value)) {
        alert("已存在")
        return
      }
      let span = document.createElement("span")
      span.innerText = userValue.value
      div.appendChild(span)
      item.data.push(userValue.value)

      span.onclick = () => {
        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 => {
    let span = document.createElement("span")
    span.innerText = subitem
    div.appendChild(span)
    span.onclick = () => {
      span.remove()
      item.data = item.data.filter(item => item !== subitem)
      console.log(span, item.data);
    }
  });
});

document.querySelector(".choice").onmouseover = () => {
  optionList.style.display = "block ";
  listDivs.forEach(allDiv => allDiv.style.display = "none");
}

optionList.onmouseleave = () => {
  optionList.style.display = "none ";
}
``
let userValue = documentquerySelectorcontent let KeywordFiltering = name 名字 class username data 嘻嘻 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿 哈哈 嘿嘿

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

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