简体   繁体   中英

Undefined Function Even though I defined it in Javascript

I'm trying to solve my assignment in NodeJs and Electron, I have an array of data in Main.js file and retrieve it to the index.html using IPC methods. There are also a button in every record/row of data and I want to set a function on this button by onclick attribute. But this gives me error when I clicked the button that function is not defined. My Code:

function myfun(){
    console.log("not working");
}
ipc.send("requestFileData");
ipc.on("responseFileData",(event,data)=>{

        // var htmldata = "";
        data.forEach(myFiles => {
            contentsTable.append(`
            <tr id="${myFiles.id}">
            <td>${myFiles.id}</td>
            <td>${myFiles.file_name}</td>
            <td><button id="${myFiles.id}" onclick="myfun()">Edit Image</button></td>
            </tr>
            `);
        });
});

when I clicked on the Edit Image button this gives me error:

Uncaught ReferenceError: myfun is not defined at HTMLButtonElement.onclick (index.html:1)

At last I have find the solution, which i would like to share:

ipc.on("responseFileData",(event,data)=>{

        contentsTable.html("");
        data.forEach(myFiles => {
            contentsTable.append(`
            <tr>
            <td>${myFiles.id}</td>
            <td class="fields">${myFiles.file_name}</td>
            <td><button class="clickedit" id="${myFiles.id}">Edit Image</button></td>
            </tr>
            `);
        });
        let editBtn = document.getElementsByClassName("clickedit");

        for(let i = 0; i < editBtn.length; i++) {
            editBtn[i].addEventListener("click", function() {
              var editId = editBtn[i].id;
              console.log(editId);
            });
          }
        });

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