javascript - 在 Javascript 中单击时从按钮的动态 ID 中获取值
问题描述
我的 .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 扩展不允许它
解决方案
- 你循环的不止一个相同的ID?这是不允许的
- 代表
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>
推荐阅读
- c++ - can't seem to link GLFW library
- apache-spark - Spark 和 CouchDB 的大数据
- r - 在 r 中使用变量作为函数参数
- javascript - 是否有可靠的方法来自动检测电子邮件中的按钮和确认代码?
- rest - 谁决定在 REST 架构上使用 HTTP 动词
- python - 使用 MAMP 和 cgi 访问表单时出错 - 调试
- datetime - 使用 PYSPARK 为 SPARK 数据框中不同“开始日期”的缺失日期创建占位符
- python - 如何将此带有比较的for循环转换为列表理解?
- python - 如何将两个熊猫数据框垂直堆叠在一起,同时保持它们各自的列名?
- sql - 关于“这里不允许使用群组功能”