首页 > 解决方案 > 在 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 扩展不允许它

标签: javascriptjavahtml

解决方案


  1. 你循环的不止一个相同的ID?这是不允许的
  2. 代表

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>


推荐阅读