Home>

I don't understand how to make the corresponding value displayed when clicking on the buttons, and not the last one. Bind should stay and overwrite window too

const buttonsNames= ["create", "delete", "click"];
    const showName= (name)=> {
        console log(name);
    }
    buttonsNames.forEach((el)=> {
        window.my= {showName: showName.bind(this, el)};
        document.body.innerHTML += `<button onclick="my.showName()">${el}</button>`;
    });
  • Answer # 1

    Suitable as a solution in certain cases:

    const buttonsNames= ["create", "delete", "click"];
        const showName= (name)=> {
            console log(name);
        }
        buttonsNames.forEach((el)=> {
            document.body.innerHTML += `<button onclick="showName(this.textContent)">${el}</button>`;
        });
  • Answer # 2

    Suitable as a solution in certain cases:

    const buttonsNames= ["create", "delete", "click"];
        const showName= (name)=> {
            console log(name);
        }
        buttonsNames.forEach((el)=> {
            document.body.innerHTML += `<button onclick="showName(this.textContent)">${el}</button>`;
        });
  • Answer # 3

    Stitchwindow.my= {showName: showName.bind(this, el)};you are constantly replacing the valuewindow.myto a new one. As a result, only the last value will be contained there.

    Try using creating a DOM element and setting its properties dynamically instead of adding elements as static HTML.

    const buttonsNames= ["create", "delete", "click"];
        const showName= (name)=> {
            console log(name);
        }
        buttonsNames.forEach((el)=> {
            var btn= document.createElement("button");
            btn.onclick= showName.bind(this, el);
            btn.innerText= el;
            document.body.appendChild(btn);
        });
  • Answer # 4

    Stitchwindow.my= {showName: showName.bind(this, el)};you are constantly replacing the valuewindow.myto a new one. As a result, only the last value will be contained there.

    Try using creating a DOM element and setting its properties dynamically instead of adding elements as static HTML.

    const buttonsNames= ["create", "delete", "click"];
        const showName= (name)=> {
            console log(name);
        }
        buttonsNames.forEach((el)=> {
            var btn= document.createElement("button");
            btn.onclick= showName.bind(this, el);
            btn.innerText= el;
            document.body.appendChild(btn);
        });