javascript - 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;
它不会改变任何事情。
谢谢您的帮助
解决方案
我们在这里面临一个经典的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
}
});
推荐阅读
- excel - 检查文件夹并比较 txt 文件的确切列表。还有一个带有文件夹选择器的公共变量,我无法在 msgbox 中显示
- reactjs - 如何在 LineChart 上正确获取 xAxis?
- xml - 如何将 DITA xml 转换为 CQ xml?
- c++ - 快速排序函数 C++ 1 参数 - 向量
- ruby-on-rails - 嵌套分组 ActiveRecord 的代码建议 | 导轨 5.2
- vb.net - 将数据从 System.Windows.Forms WebBrowser 传递到单独的网页
- python - 如何使用python对dict进行排序?
- c++ - 不知道如何在我的程序中添加循环...?
- javascript - 在弹出窗口的父窗口中打开 iframe 的链接
- c# - 如何在 ASP.Net Web API 中摄取大量日志