Search code examples
javascripthtmljquerygoogle-chrome-extension

Jquery element with onclick to inline string


the following code is not working:

  return targets
    .map(
      (target, i) => `
      <tr>
        <td>${target.name}</td>
        <td>${target.coordinates.join(':')}</td>
        <td>${new Date(target.lastscan).toLocaleString()}</td>
        <td>
          ${$('<button class="icon_nf icon_espionage" type="submit"></button>)').on('click', () => console.log('Test')).html()}
        </td>
      </tr>
    `
    )
    .join('');

With the html() function at the end the button element will not be rendered. When i wrap the button into another element the button will be rendered, but the onclick function is not working.

This code comes from my chrome extension i try to create.

Do you know how i can render a button with onclick without adding a event listenes after i added the button to the dom?


Solution

    1. .html() won't convert listeners added via .on(), but using html attribute listeners won't work in extensions anyway because it's forbidden by the default CSP for extensions, more info.

    2. When there are lots of similar elements it's best to use event delegation: attach just one listener on the common parent element.

    You can construct an html string of the entire table, pass it to jQuery, then add a listener:

    const table = $(`
      <table>${targets.map(t => `
        <tr>
          <td>${t.name}</td>
          <td>${t.coordinates.join(':')}</td>
          <td>${new Date(t.lastscan).toLocaleString()}</td>
          <td>
            <button class="icon_nf icon_espionage" type="submit"></button>
          </td>
        </tr>
      `).join('')}
      </table>
    `).on('click', 'button', e => console.log('Test', e.target));