简体   繁体   中英

addEventlistener for buttons does not work properly with more than one button

I want to create a script where I can upload files via event listener drop .

Everytime a file is dropped, a new table row has to be created with a save/edit button. These buttons need event listeners for click , but the problem is that the event listener works only on the last button added to the table.

I have made a simplified example of my problem. The function clickEventSaveButton() contains an .addEventlistener , with an anonymous function. For now it just executes a console log, but only for the button in the last table row. Everytime a new button is created, the old one stops working.

JS:

'use strict';

const dragArea = document.getElementById('dragArea');
const fileTable = document.getElementById('fileTable');
const fileTableBody = fileTable.querySelector('tbody');
let id = 0;

dragArea.addEventListener('dragover', (e) =>  {
    e.preventDefault();
    e.stopPropagation();
});

dragArea.addEventListener('drop', (e) => {
    e.preventDefault();
    e.stopPropagation();

    // Add table row
    fileTableBody.innerHTML += createFileTableRow(id, 'placeholder');

    clickEventSaveButton(id);

    id++;
});

function clickEventSaveButton(id) {
    let saveButton = document.querySelector('.file-save a[data-id="'+id+'"]');
    console.log(saveButton);
    console.log(id);
    saveButton.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        console.log('Save Button (ID:'+id+') pressed!');
    });
}

function createFileTableRow(id, name) {
    return `
        <tr data-id="${id}">
            <td class="file-name">${name}</td>
            <td class="file-save">
                <a data-id="${id}" class="button is-info is-small">Save</a>
            </td>
        </tr>
    `;
};

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self';">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
    <script defer src="test.js"></script>
  </head>

  <body>
    <div class="columns"><div class="column is-half is-offset-one-quarter">
      <h1>Work in progress</h1>
      <div id="dragArea" class="box has-background-info-light has-text-centered py-6">
        Drag .xlsx files here!
      </div>

      <hr>
        <h3 id="fileTableTitle">No files loaded...</h3>
        <table id="fileTable" class="table table is-fullwidth is-hoverable">
          <thead><tr><th>File</th><th>Save File</th></tr></thead>
          <tbody></tbody>
        </table>

      <hr>
    </div></div>
  </body>
</html>

So, thanks to Patrick Evans I was able to solve the issue that bugged me for some hours.

Instead of innerHTML I have to use insertAdjacentHTML .

Solution:

fileTableBody.insertAdjacentHTML('beforeend', createFileTableRow(id, 'placeholder'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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