Javascript Document Write Button Inside Function Used By Another Function Not Working
Solution 1:
This is one of the many reasons not to use onxyz
-attribute-style event handlers: They require that any functions you use in them be globals. Globals are Bad Things™. Your functions apparently aren't globals, which is a Good Thing™.
Separately, document.write
has essentially no place in web development in 2016 (or 2006). Instead, use the DOM. One advantage of doing that in your case is that it means clickAttack
no longer has to be a global:
functionclickStart() {
var input = document.createElement("input");
input.type = "button";
input.value = "attack!";
input.addEventListener("click", clickAttack, false);
document.body.appendChild(input);
}
Solution 2:
Or you can use jquery like this.
$(document).ready(function(){
$('body').on('click', '.myButton' , clickAttack);
});
functionclickStart(){
$( "body" ).append( $( "<input type='button' value='attack!' class='myButton'/>"));
}
functionclickAttack(){
alert("hello");
}
<input type='button' value='add!' onClick='clickStart();' />
Solution 3:
Hello I recommend you to use jQuery library. The code will be simple for you.
My solution for you is here in jsFiddle
I used self invoke function where init function register event listener.on()
click and this call attack function
If you have any questions feel free to contact me.
The js code:
(function(){
'use strict';
functionattack() {
$('#logger').append('Attacked!<br>');
};
functioninit() {
$('#attackBtn').on('click', function() {
attack();
});
};
init();
})();
Post a Comment for "Javascript Document Write Button Inside Function Used By Another Function Not Working"