2 回答
TA贡献1906条经验 获得超10个赞
您需要处理程序来获取对单击的按钮(或其容器)的引用,以便它可以删除容器 - 处理程序需要一个参数或者它需要检查事件。
另一个问题是您使用的是内联处理程序,它有太多问题。改为使用 Javascript 附加侦听器,在处理程序内部,您将能够cell在外部范围内引用 ,并且.remove()它:
button.onclick = () => cell.remove();
var mission = {
text: 'text',
date: 'date',
time: 'time'
};
const rows = document.getElementById('rows');
const cell = document.createElement('div');
cell.innerHTML = '<button type="button" class="btn btn-default" aria-label="Right Align"><span class="glyphicon glyphicon-remove" aria-hidden="true">Remove</span></button><textarea></textarea><div><input><input></div>';
rows.appendChild(cell);
const [button, textarea, dateinput, timeinput] = cell.querySelectorAll('button, textarea, input');
button.onclick = () => cell.remove();
textarea.value = mission.text;
dateinput.value = mission.date;
timeinput.value = mission.time;
<div id="rows"></div>
请注意,文档中具有特定 ID 的元素不应超过一个。rows在这种情况下,无论如何都不需要容器以外的任何 id 。
TA贡献1874条经验 获得超12个赞
我建议创建按钮,createElement以便您可以收听点击事件,并将其附加到容器,cell如下所示
// The cell which contains the button itself is being passed as a parameter
createRemoveButton = (cell) => {
const button = document.createElement('button');
button.addEventListener('click', _ => {
document.getElementById('rows').removeChild(cell);
});
// Apply any styles needed...
button.style.height = '20px';
button.innerHTML = 'Remove';
return button;
}
然后,当您创建div-cell元素时,只需将生成的按钮附加到click事件的回调中。
// ...
const rows = document.getElementById('rows');
const cell = document.createElement('div');
const id = document.createAttribute('id');
id.value = 'div-cell';
cell.setAttributeNode(id);
const btn = createRemoveButton(cell);
cell.innerHTML = '<textarea></textarea><div><input><input></div>';
cell.appendChild(btn);
rows.appendChild(cell);
//...
添加回答
举报
