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 badges2 Answers
Reset to default 2You 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
版权声明:本文标题:javascript - Create Button with Function after clicking - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745170243a2645929.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论