可以尝试使用事件委托,将点击事件绑定在父元素上,通过事件冒泡来处理子元素的点击事件。这样可以避免为每个span都绑定一个点击事件。

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

div.onclick = (event) => {
  if (event.target.tagName === 'SPAN') {
    event.target.remove();
    item.data = item.data.filter(item => item !== event.target.innerText);
  }
}

item.data.forEach(subitem => {
  let span = document.createElement("span")
  span.innerText = subitem
  div.appendChild(span)
});

通过将点击事件绑定在父元素div上,利用事件冒泡机制,点击span时会触发div的点击事件,然后判断点击的元素是否是span,如果是则移除该span并更新item.data。这样可以实现删除功能,并避免了为每个span都绑定一个点击事件

lionclick = = listDivsforEachallDiv = allDivstyledisplay = none; divstyledisplay = block; optionListstyledisplay = none; documentquerySelectorconfirmonclick = = if itemd

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

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