如何解决呢?
第一:onclick
<body><button onclick="AddJob()">添加工作经历</button><button onclick="GetJobs()">获取全部工作</button><div id="joblist"><div id="job1" class="job"><input name="CompanyName" type="text" value="公司1" /><button onclick="DelJob(1)">删除</button></div></div><script type="text/javascript">//添加工作经历function AddJob() {var timestamp = parseInt((new Date()).valueOf()); //唯一的标识console.log(parseInt((new Date()).valueOf()));document.getElementById("joblist").innerHTML +=`<div id="job` + timestamp + `" class="job"><input name="CompanyName" type="text" value="公司` + timestamp + `" /><button onclick="DelJob(` + timestamp + `)">删除</button></div>`;}//删除工作经历function DelJob(timestamp) {document.getElementById("job" + timestamp).remove();}//获取全部工作经历function GetJobs() {var jobs = document.getElementsByClassName("job");var arr = [];for (var i = 0; i < jobs.length; i++) {var job = jobs[i];var companyName = job.children[0].value;arr.push(companyName);}console.log(arr);alert(arr);}</script></body>
第二种:
document.getElementById('joblist').addEventListener('click', function (ev) {var target = ev.target || ev.srcElement;if (target.nodeName.toLowerCase() == 'button') {var e = document.getElementById(target.parentNode.id);document.getElementById("joblist").removeChild(e);}});
推荐第二种