Javascript 无法从生成的列表中获取元素
因此,我开始了一个程序,在一个无序列表中生成一个值列表,用删除按钮删除每行列表中相应的条目。当我试图在单击按钮时获取相应元素的id时,它总是返回null,我不知道为什么 单击按钮时,通过以下功能生成值列表:Javascript 无法从生成的列表中获取元素,javascript,html,Javascript,Html,因此,我开始了一个程序,在一个无序列表中生成一个值列表,用删除按钮删除每行列表中相应的条目。当我试图在单击按钮时获取相应元素的id时,它总是返回null,我不知道为什么 单击按钮时,通过以下功能生成值列表: const random = () => { let remove = document.getElementById("generate"); remove.remove(); document.body.appen
const random = () => {
let remove = document.getElementById("generate");
remove.remove();
document.body.appendChild(list);
while (chosenNames.length < 20) {
let num = Math.floor(Math.random() * names.length)
let inputName = names[num]
if (chosenNames.indexOf(inputName) === -1) {
chosenNames.push(inputName)
};
};
const nameGen = (name) => {
let add = document.createElement("li");
let deleteButton = document.createElement("button");
deleteButton.setAttribute("class", `deleteButton`);
deleteButton.setAttribute("onclick", `deleteClick(${name})`);
deleteButton.innerText = "X";
add.setAttribute("id", name);
add.setAttribute("class", name);
list.appendChild(add);
add.innerHTML += `${name} `;
add.appendChild(deleteButton);
};
chosenNames.forEach(nameGen);
};
我还没有完全解决它的删除部分,所以我不确定这是否是错误的,但不管怎样,控制台中的输出总是空的。因此,不知何故,这个函数没有获取具有正确id的元素,我也不知道为什么。点击按钮会显示错误
未捕获的TypeError:未能在“节点”上执行“removeChild”:参数1不是“节点”类型
考虑到参数为null,这并不奇怪
任何帮助或见解都将不胜感激:k和d是未分配的变量。在代码中,将${name}更改为${name},以便生成的click事件处理程序传递字符串而不是未赋值变量。k和d是未赋值变量。在代码中,将${name}更改为${name},以便生成的click事件处理程序传递字符串而不是未赋值变量。设置onclick属性时,需要在名称值周围输出引号,以便函数调用接收字符串值:
deleteButton.setAttribute("onclick", `deleteClick('${name}')`);
设置onclick属性时,需要在名称值周围输出引号,以便函数调用接收字符串值:
deleteButton.setAttribute("onclick", `deleteClick('${name}')`);
deleteButton.setAttribute("onclick", `deleteClick('${name}')`);