Javascript - Calling a function -
<div id='dependent'> <input type="button" value="add" id='btn' onclick='addfunction()' /> </div> <script type="text/javascript"> var = 1; var b = 1; var c = 1; function addfunction() { var c1 = document.createelement('input'); c1.type = "checkbox"; c1.id = "a" + a++; var c2 = document.createelement('input'); c2.type = "checkbox"; c2.id = "b" + b++; var c3 = document.createelement('input'); c3.type = "checkbox"; c3.id = "c" + c++; var c4 = document.createelement('br'); document.getelementbyid("dependent").appendchild(c1); document.getelementbyid("dependent").appendchild(c2); document.getelementbyid("dependent").appendchild(c3); document.getelementbyid("dependent").appendchild(c4); // c1.onclick = dep(); // function dep() { alert(this.id); } c1.onclick = function () { alert(this.id); }; } </script>
when call function this,
c1.onclick = function () { alert(this.id); };
it works expected. i.e, when click on checkbox, alert appears id.
but if call function in way,
c1.onclick = dep(); function dep() { alert(this.id); }
the alert appears, when click on 'add' button(on calling addfunction()). why?
because you're executing dep()
, assign return value c1.onclick
.
if want assign function itself, don't call it:
c1.onclick = dep;
Comments
Post a Comment