简体   繁体   中英

Create Button with Function after clicking

I've got some functions...

function myFunction()
{
    var btn = "<input type='button' onclick='sf();'>";
    var t = document.createTextNode("FINISH GAME");
    btn.appendChild(t);
    document.body.appendChild(btn);
};
function sf(){window.alert("You finished the game!")};

..and a button that activates the first function.

<button onclick="myFunction()">Click Me!</button>

So when I click on the "Click Me"-button, another button should be created, with the text "FINISH GAME". When clicking on that second button, the text "You finished the game!" should be alerted. But clicking on the first button, nothing happens. Where's the coding error? Where did I forget a comma? ;)

You are creating input element in wrong way.

function myFunction()
{
    var btn = document.createElement('input');
    btn.setAttribute('type' , 'button');
    btn.setAttribute('value', 'FINISH GAME');
    document.body.appendChild(btn);
    btn.addEventListener('click','sf',false);

 };
function sf(){window.alert("You finished the game!")};

how to create element in JavaScript

It is because your variable btn is not a DOM element but string. You can create input element and set all its attributes like this:

function myFunction() {
    var btn = document.createElement('input');
    btn.setAttribute('type', 'button'); // input element of type button
    btn.setAttribute('value', 'FINISH GAME');
    btn.onclick = sf;
    document.body.appendChild(btn);
};

or:

function myFunction() {
    var btn = document.createElement('button'); // button element
    var t = document.createTextNode("FINISH GAME");
    btn.appendChild(t);
    btn.onclick = sf;
    document.body.appendChild(btn);
};

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