如何使用普通的javascript定位DOM中非唯一的,动态生成的元素?

问题描述

我有一个input字段,它将输入的字符串推入数组,然后从数组中的每个对象生成一个<li>。我还为每个列表项添加一个点击侦听器。

单击侦听器和动态生成的列表项可以按预期工作,但唯一可以使单击侦听器执行的功能是console.log,因为我不知道如何定位刚刚定位的列表项点击。

我想定位要单击的项目,以添加一个class,将其从text-decoration更改为line-through。我已经准备好了一切,我只需要弄清楚如何使用DOM定位点击的项目。

我尝试过document.querySelectorAll("li"),但是只返回一个Nodelist。我也尝试过其他所有可以想到的DOM方法,当调用this作为函数中的参数时,我也尝试过。无法使每个生成的列表项都唯一,因为它们都具有相同的类和相同的父项。

如果我通过说document.getElementByTagName("ul").firstChild.classList.add("strikethrough");来定位第一个孩子,那么一切正常,这意味着代码没有错误,但是当我有10个列表项并单击第4个项目时,该代码将不起作用。

我想包含我的整个代码,但我不想混淆这个问题,因为每一行都在发生很多事情,并且每个函数都在处理多个进程。再一次,我想重申一切正常,只是缺少最后一个链接,即如何定位刚刚用DOM(或类似方法)单击过的非唯一动态生成的元素。

这是有问题的代码段,它应该包含您需要了解的有关代码的所有信息:

let plannerItems = [];
let backwardsArray = plannerItems.reverse();

function createList() {
  for (var i = 0; i < backwardsArray.length; i++) {
    var plannerItem = backwardsArray[i];
    var nextItem = document.createElement("li");
    nextItem.innerHTML= plannerItem;
    nextItem.classList.add("listItems");
    nextItem.addEventListener("click",function(event) {
      crossOff();
    });
    document.getElementById("list").prepend(nextItem);
  };
};

function crossOff() {
  document.getElementById("list").firstChild.classList.add("strikethrough");
   ////This is where I would put my DOM method....If I had one... ////
};

因此,如您所见,注释上方的最后一行代码是我需要用正确的DOM方法替换的代码。我也尝试过nextItem.classlist.add("strikethrough");,但这只会将该类添加到第一个孩子,而不是单击的文本上。

解决方法

您可以使用event来访问从事件中单击的元素。currentTarget,可以将其传递到crossOff()中:

let plannerItems = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'];
let backwardsArray = plannerItems.reverse();

function createList() {
  for (var i = 0; i < backwardsArray.length; i++) {
    var plannerItem = backwardsArray[i];
    var nextItem = document.createElement("li");
    nextItem.innerHTML= plannerItem;
    nextItem.classList.add("listItems");
    nextItem.addEventListener("click",function(event) {
      crossOff(event.currentTarget);
    });
    document.getElementById("list").prepend(nextItem);
  };
};

function crossOff(item) {
  item.classList.add("strikethrough");
};

createList();
.strikethrough {
  text-decoration: line-through;
}

li {
  cursor: default;
}
<ul id="list">
</ul>