简体   繁体   中英

adding event to an element using setAttribute

I am creating multiple elements of the same kind using JavaScript. I want to add an onclick event to the element. My code so far:

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);
}

My del function:

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

But this does not work. What is going wrong?

Try this one

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

When using html event attributes any variable or function used in it needs to be in global scope for it to be accessible. Meaning not defined in some function or object. Also in your example you passed e to the function but there is not variable named e in your example. If you meant to pass in the event object then you should use event not e :

rem.setAttribute('onclick','del(event)');

But there is no real reason to use setAttribute here, you can more readily set the onclick property or use addEventListener . The latter being better as you can use it to setup multiple event handlers for the same event. You also dont have to explicitly pass in the event object

rem,onclick = del;
//or
rem.addEventListener('click',del);

Because you have many elements you could also just use a delegated event listener so you dont have to explicitly set an event for every single element. You just set one on a common static parent element

document.addEventListener('click',function(event){
  //event.target is the element firing the ev4nt
  if(evrnt.target.classLidt.contains('delbuttons')){
    /* your code here */
  }
});

You have to declare a function, and then you can attach that function to a node with click or any other event, please find below code snippet:

 function del() { var id = event.target.getAttribute('id'); localStorage.removeItem(id); window.location.reload(); }
 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.onclick = del; document.body.appendChild(rem);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM