单击时如何检索HTML集合的索引?

时间:2018-09-13 16:30:01

标签: javascript jquery html frontend

每当单击index时,尝试使函数获取edit icon。即使有使用closure的解决方案,但当编辑图标超过一个时,仍然无法处理我的情况并得到错误的结果。

当我有三个图标时,控制台输出:

  1. (3) 0
  2. (2) 1
  3. 2

需要知道为什么使用控制台。

这里是js的小提琴,上面有完整的代码:https://jsfiddle.net/c2L4buj6/5/

示例代码 JS

function clickEnable(input, title, url, plus, editIcon, anchorEdit, edit)
{
  for(let i = 0; i < editIcon.length; i++){
      editIcon[i].addEventListener("click", function(i){
        console.log(i);
      }.bind(null, i));
  }
}

更新 为了更清楚地显示错误,上载了最新情况的照片。在照片中,有三个框,当单击编辑图标时,它会返回正确的值,但也会返回正确值的副本。我想知道是什么原因造成的。

Here is the error image

1 个答案:

答案 0 :(得分:0)

您不会删除旧的事件侦听器,因此所有先前添加的元素都会得到重复。

一种解决方案(根据您的小提琴{tested):

function clickEnable(input, title, url, plus, editIcon, anchorEdit, edit)
{
  let i = editIcon.length - 1;
  editIcon[i].addEventListener("click", function(){
    console.log(i);
  });
}