简体   繁体   English

模板文字内的事件回调

[英]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.大家好,我是 javascript 新手,我正在尝试使用模板文字对用户的点击事件执行回调函数。 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. row 方法由另一个传递项目和回调函数的类调用。

 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.我认为你想要实现的更好的方法是从row而不是 HTML 字符串返回一个元素。 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.然后可以使用appendafter或类似的东西append其添加到 DOM 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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