(Vanilla JS)使用click事件侦听器捕获数组元素的索引吗?

时间:2018-06-24 04:30:14

标签: javascript arrays addeventlistener

所以我正在制作一个简单的RPG游戏,所以我有意使用Vanilla JS,因为我想重新审视/加强一些基础知识。我可以访问单击元素的一些数据,但是我特别希望索引。我正在访问目标的子节点,但希望能够获取索引。这是我的glitch.com链接:https://green-cricket.glitch.me/

chooseEnemy: function() {
let villiansDiv = document.getElementById('villians-div');
villiansDiv.addEventListener('click', function(event) {
  let eventClicked = event.target;
  let villianName = event.toElement.childNodes[0].data;
  let children = villiansDiv.children;   

  for (let i = 0; i < villians.length; i++) {
    if (villianName === villians[i].name) {
      views.updateLog('You chose ' +  villians[i].name);
      battleArr.push(villians[i]);
      if (battleArr.length === 1) {
        for (let i = 0; i < children.length; i++) {
          children[i].setAttribute('class', 'inactive');
        }
      } else {
          for (let i = 0; i < children.length; i++) {
            children[i].classList.remove('inactive');
          }
        }
      if (villianName === "Fisherman") {
        let res = villians.splice(0, 1);
        // return;
      }
      else if (villianName === "Farmer") {
        let res = villians.splice(1, 1);
        // return;
      }
      else if (villianName === "Samurai") {
        let res = villians.splice(2, 1);
        // return;
      }
      else if (villianName === "Kuma") {
        let res = villians.splice(3, 1);
        // return;
      }
      else {
        views.updateLog('Click an enemy\'s name');
      }
      // views.updateVillians();
      views.updateChosenEnemy();
    } 
  }
});
}

0 个答案:

没有答案