简体   繁体   中英

Event Callback Inside Template Literal

Hi everyone I'm new to javascript and I'm trying to execute a callback function on the user's click event using template literals. However the callback is being executed on the template's evaluation.

The row method is called by another class which is passing the item and the callback function.

 class Clazz { row(item, deleteCallback){ return `<a href="#" onClick="${deleteCallback(item.requestId)}"></a>` } }

Can anyone help me ?

I think a better approach to what you're trying to achieve is to return an element from row instead of an HTML string. Like so:

class Clazz {
  row(item, deleteCallback){
    const a  = document.createElement('a');
    a.href = '#';
    a.onclick = () => deleteCallback(item.requestId);
    return a;
  }
}

This could then be added to the DOM using append , after or something similar.

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