javascript - 使用 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();
}
但这不起作用。出了什么问题?
解决方案
试试这个
rem.onclick = function(e) {del(e);};
推荐阅读
- c# - 来自 .csv 的 StreamReader - “外来”字符和空白值显示为“?”
- r - 覆盖自定义情节的美学
- c# - 使用 DPAPI 更新 XDocument 不起作用?
- certificate - 使用 Certum 证书自动化 (EV) 代码签名
- c# - SQL 查询在 C# 中执行,但不返回任何结果
- python-3.x - Pandas Dataframe:如果相应的“年”是闰年,则将“天”的值减少 1
- angular - 名称为“句点”的表单控件没有值访问器
- heroku - 我的机器人突然不再从 heroku 工作了,它不再出现“在线”
- java - 从批处理方法调用时未调用使用 @Retryable 注释的方法
- javascript - 两年之间的每个月循环