Javascript: two .onclick with different functions -
i'm trying familiarize myself javascript, , behavior i've seen trying work on calculator.
setup(); function setup(){ element = document.getelementbyid("1"); console.log(element); if(element.innerhtml === "1"){ var test = element; element.onclick = test1; element.onclick = test2; } } function test2(){ console.log("test2 function"); } function test1(){ console.log("test1 function"); }
how come if run this, test2 function returns log, return last function called, or behavior of .onclick function?
now if try calling test1 function inside test2 this, still doesn't work.
function test2(){ console.log("test2 function"); test1; }
but if instead this
function test2(){ console.log("test2 function"); test1(); }
it logs both of them. how come? i'm used ruby if relevant.
==================================
also question, difference between
function test(){ return function(){ console.log("test!"); } }
to
function test(){ console.log("test"); }
because you're overriding onclick
function when bind test2
. if need run both when clicking, wrap binding inside anonymous function , call both:
if(element.innerhtml === "1") { element.onclick = function() { test1(); test2(); }; }
alternatively, can use event bindings instead of assigning anonymous function element's onclick
property using addeventlistener
. has added advantage can remove either or both of functions independently:
if(element.innerhtml === "1") { element.addeventlistener('click', test1); element.addeventlistener('click', test2); }
Comments
Post a Comment