1

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?

1 Answer 1

1
  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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.