首页 > 解决方案 > 使用 setAttribute 向元素添加事件

问题描述

我正在使用 JavaScript 创建多个相同类型的元素。我想向onclick元素添加一个事件。到目前为止我的代码:

for(let i=0;i<localStorage.length;i++)
{
var rem=document.createElement("button");
rem.innerHTML='<i class="fa fa-trash-o" aria-hidden="true"></i>';
rem.setAttribute('background-color','white');
rem.setAttribute('id',localStorage.key(i));
rem.setAttribute('class','delbuttons');
rem.setAttribute('onclick','del(e)');
document.body.appendChild(rem);
}

我的del功能:

function del(event) {
  var id = event.target.getAttribute('id'); 
  localStorage.removeItem(id);
  window.location.reload();
}   

但这不起作用。出了什么问题?

标签: javascriptevent-handling

解决方案


试试这个

 rem.onclick = function(e) {del(e);}; 

推荐阅读