gpt4 book ai didi

javascript - 在 Javascript 中单击时从按钮的动态 ID 获取值

转载 作者:行者123 更新时间:2023-12-01 16:19:01 24 4
gpt4 key购买 nike

我的 .js 文件包含

function ngForEducationDetails() {
let value = '';
educationdetails.forEach((x , i) => {
value +=
`<div class=""> <p class="f-14 details-subheaders"> ${x.institutename}
<button class="edit-icon xd" style="float: right" id="editSingleEducation" value="${i}"> </button>
<p class="f-12">${x.fieldofstudy} </p>
<p class="f-12 mb-4"> ${x.startdate} - ${x.enddate} </p> </div>` ;
});

document.getElementById('fos').innerHTML = value; };

ngForEducationDetails();

在我的 html 文件中

 <span for="fos" id ="exd" class="col-12"></span> 

我希望在按钮单击时,我希望 id 的值与其关联。下面的功能不起作用。帮助我:)

  document.getElementById('editSingleEducation').addEventListener('click', function() {
var indexvalue = document.getElementById('editSingleEducation').value
console.log(indexvalue , "indexvalue")
})

注意:我不能使用内联函数,因为我在 chrome 扩展中这样做,而 chrome 扩展不允许它

最佳答案

  1. 您正在循环多个相同的 ID?这是不允许的
  2. 委托(delegate)
<小时/>
document.getElementById('fos').addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("edit-icon")) {
console.log(tgt.value);
}
})

改进的代码,在数据属性中使用 id:

const educationdetails = [{
"candidateeducationid": 4,
"institutename": "Mumbai University",
"degree": "Bsc",
"fieldofstudy": "Science",
"startdate": "2019-01-01T00:00:00.000Z",
"enddate": "2020-01-01T00:00:00.000Z",
"score": null,
"activities": null
},
{
"candidateeducationid": 5,
"institutename": "LA",
"degree": "MCA",
"fieldofstudy": "Science",
"startdate": "2018-01-01T00:00:00.000Z",
"enddate": "2019-01-01T00:00:00.000Z",
"score": null,
"activities": null
},
{
"candidateeducationid": 6,
"institutename": "Abu Dhabi University",
"degree": "Associate of Arts and Sciences",
"fieldofstudy": "Science",
"startdate": "2018-01-01T00:00:00.000Z",
"enddate": "2020-01-01T00:00:00.000Z",
"score": null,
"activities": null
}
];

function ngForEducationDetails() {
let value = educationdetails.map((x, i) => `<div class=""> <p class="f-14 details-subheaders"> ${x.institutename}
<button class="edit-icon xd editSingleEducation" data-id="${x.candidateeducationid}" style="float: right">${x.candidateeducationid}</button>
<p class="f-12">${x.fieldofstudy} </p>
<p class="f-12 mb-4"> ${x.startdate} - ${x.enddate} </p> </div>`);

document.getElementById('fos').innerHTML = value.join("");
}


ngForEducationDetails()

document.getElementById('fos').addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("edit-icon")) {
console.log(tgt.dataset.id);
}
})
div {
border: 1px solid black;
padding: 5px;
}
<div id="fos"></div>

关于javascript - 在 Javascript 中单击时从按钮的动态 ID 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62318979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com