Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

javascript - 将onclick事件添加到模板(add onclick event to template)

I have problem that cannot add event onclick to my element.(我有无法将事件onclick添加到我的元素的问题。)

If I call it like that:(如果我这样称呼它:) <td onclick="${console.log('bam')}">X</td> Event is called immediately, so I assumed that if I do it like this:(事件会立即被调用,因此我假设如果这样做的话:) <td onclick="${() => console.log('bam')}">X</td> It will work after click but unfortunately with such a code it stops to work at all.(单击后可以使用,但是不幸的是,使用这样的代码,它完全无法使用。) Anyone knows how to fix it?(有人知道如何解决吗?) Oh And I wish to achieve it without jQuery.(哦,我希望在没有jQuery的情况下实现它。) Whole code:(整个代码:) this.device.error_log.map((el, i) => { if (el.message.component == "displays") { return (result += ` <tr error_id="${i}"> <td> ${this.device.error_log[i].message.component} </td> <td> ${this.device.error_log[i].message.info} </td> <button onclick="${() => console.log('bam)}"> X </button> </tr>`); } }); this.error_table.innerHTML += result   ask by Jacki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The general idea would be create the elements inside the function, assign event handlers to them, and then append them to the table:(通常的想法是在函数内部创建元素,为它们分配事件处理程序,然后将它们附加到表中:)

this.device.error_log.forEach((el, i) => { if (el.message.component == "displays") { const tr = document.createElement('tr'); tr.setAttribute('error_id', i); tr.innerHTML = ` <td> ${this.device.error_log[i].message.component} </td> <td> ${this.device.error_log[i].message.info} </td> <button> X </button>`; tr.querySelector('button').onclick = () => this.bam(); this.error_table.appendChild(tr); } }); Note that you should only use .map when you need to create a new array.(请注意,仅在需要创建新数组时才应使用.map 。) Here, you want to perform side effects (alter the DOM), so you should use .forEach instead.(在这里,您要执行副作用(更改DOM),因此应改用.forEach 。) While it would be possible to change things around to use an inline handler instead, inline handlers are generally considered to be quite poor practice - they lead to fragile code, require global pollution, have string escaping issues, have scoping problems, and have a weird with mechanism, among other things.(尽管可以改变周围的内容以使用内联处理程序,但是内联处理程序通常被认为是非常差的做法-它们会导致脆弱的代码,需要全局污染,存在字符串转义问题,具有范围问题以及很奇怪with机制,等等。) Better to attach the listener explicitly.(最好显式附加侦听器。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...