admin管理员组

文章数量:1414922

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 ma? ;)

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 ma? ;)

Share Improve this question asked Jan 3, 2016 at 21:37 J_from_HollandJ_from_Holland 771 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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);
};

本文标签: javascriptCreate Button with Function after clickingStack Overflow