vendredi 13 février 2015

call a function defined inside self-invoking function


I have a self-invoking function to hold all my javascript code. (like suggested by book)


Inside this function, i created a button, this button has onclick="myfunction()" attribute set. like this:



(function() {
var x = 4;
var btn = document.createElement('button');
btn.type = "button";
btn.style.width = "100";
btn.textContent = "click me";
btn.id = "bid";
btn.setAttribute('onclick', "myfunction()");
document.body.appendChild(btn);

function myfunction() {
alert(x);
}

})();


But then when i click on created button, myfunction() can not be found. the message is:


ReferenceError: Can't find variable: myfunction


Then I moved myfunction() out like this:



(function() {
var x = 4;
var btn = document.createElement('button');
btn.type = "button";
btn.style.width = "100";
btn.textContent = "click me";
btn.id = "bid";
btn.setAttribute('onclick', "myfunction()");
document.body.appendChild(btn);

})();

function myfunction() {
alert(x);
}


Now it can find myfunction(), but the alerted x value is something like [object HTMLSelectElement], not what i expected.


I am kind of confused about functions inside self-invoking functions.





Aucun commentaire:

Enregistrer un commentaire