Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add onclick event to template

I have problem that cannot add event onclick to my element. 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. 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
like image 356
Jacki Avatar asked Dec 03 '25 18:12

Jacki


1 Answers

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. Here, you want to perform side effects (alter the DOM), so you should use .forEach instead.

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. Better to attach the listener explicitly.

like image 194
CertainPerformance Avatar answered Dec 06 '25 09:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!