首页 > 解决方案 > forEach里面的onclick,value参数只指最后一个元素

问题描述

我的 html 中有一个锚点列表,我想让它们的 href 可编辑。一切都很好,但验证步骤(最后一次点击)是指最后一个锚点而不是当前锚点

var anchors = document.querySelectorAll('.home-content a');

var col = document.querySelectorAll('.home-content > article');

anchors.forEach((k)=> {

    let linkpanel = document.getElementById('link-edit-panel'); //This element is a single div in my html

    let linkpanelvalidate = document.getElementById('validate-link'); //the button inside the said div

    let editinput = linkpanel.querySelector('input'); //the input inside this div

    //For each anchors, I add a button that will let user show the "linkpanel" div to edit the href of this anchor
    let editbut = document.createElement('div');
    let linktxt = k.href;
    editbut.classList.add('edit-but','toremove');
    editbut.innerHTML = "<i class='fas fa-link'></i>";

    //I put this new element to the current anchor
    k.appendChild(editbut);
    console.log(k); // this to show me the full list of anchors

    /* PROBLEM START HERE */
    
    //click on the "edit" button
    editbut.onclick = ()=>{

        console.log(k); //Here, it shows the good anchor!

    }

    //click on the "validate" button
    linkpanelvalidate.onclick = ()=>{

        console.log(k); //Here, it shows the very last anchor...
    }
});

我试图将元素放在一个常量内

const ttt = k;

它不会改变任何事情。

谢谢您的帮助

标签: javascript

解决方案


我们在这里面临一个经典的forEach冒泡误解(我盲目地没有看到它)

当点击验证按钮时,调用是从“主”气泡(如果你需要描绘它,在循环函数之外)进行的,所以很自然,当我们在控制台中打印值时,它会返回最后一次出现的循环例如。

解决方案

有很多解决方案,您可以将这些值存储在一个数组中,以便以后使用它们中的每一个

var arr = [];
node.forEach((v)=>{
  arr.push(v);
});

或者,您不想像我一样处理数组并希望保持简单,并且您在forEach循环事件期间创建按钮,就像这样

node.forEach((v)=>{
  let btn = document.createElement('button');
  document.body.appendChild(btn);
  btn.onclick = ()=> {
    console.log(v); //it is the current value, not the last one
    //you can create another button here and put his onclick here, the value will still remains etc
  }
});

推荐阅读