将Javascript函数添加到Dom元素

svmlkihl  于 2022-12-28  发布在  Java
关注(0)|答案(3)|浏览(143)

我创建了一个button元素并添加了一个click事件,但click事件从未触发,因此函数deleteFile从未被调用。
下面是我的代码:

let innerButtonDiv = document.getElementById("fi");
var innerButtonDelete = document.createElement("button");
innerButtonDelete.innerText = "Del";
innerButtonDelete.onclick = 'deleteFile("f")';
innerButtonDiv.appendChild(innerButtonDelete);

出了什么问题?如何正确地执行此操作,以便调用函数deleteFile

xxb16uws

xxb16uws1#

单击是不能指定为属性的事件。
附加一个监听器,并使用正确的语法,像这样-

innerButtonDelete.addEventListener('click', () => {
  deleteFile("f")
});
jjjwad0x

jjjwad0x2#

let innerButtonDiv = document.getElementById("fi");
var innerButtonDelete = document.createElement("button");
innerButtonDelete.innerText = "Del";
innerButtonDiv.appendChild(innerButtonDelete);
innerButtonDelete.addEventListener("click", () => deleteFile("f"))
r6vfmomb

r6vfmomb3#

“onclick”接受一个函数。请尝试以下操作:

let innerButtonDiv = document.getElementById("fi");
var innerButtonDelete = document.createElement("button");
innerButtonDelete.innerText = "Del";
innerButtonDelete.onclick = () => deleteFile('f');
innerButtonDiv.appendChild(innerButtonDelete);

相关问题