I am sure many of you reading this may have seen this kind of code before:
window.onload = SayHi; function SayHi(){ alert('hi'); }
This code assigns a function that will execute when the page is finished loading. Pretty simple and straight-forward. However say we need something more complex, like take elements that already have onclick events and need to re-assign/change their onclick methods for any number of reasons on the client-side. For example:
//Assuming this already had an 'onclick' event like 'onclick=SayHi();' var radioButton = document.getElementById('myRadioButton'); //Now lets say we wanted to change the onclick functionality or whatever... radioButton.onclick = SayHi2;
Everything works as expected our radio button now has a new function whenever it is called. This is where it gets tricky. Say we have a function that needs to pass in arguments to our SayHi2 method. Like 'name'.
function SayHi2(name){ alert(name); }
We cannot assign this new function to our existing code like this.
var radioButton = document.getElementById('myRadioButton'); radioButton.onclick = SayHi2(name);
It will drive a person crazy to figure out that when this code gets executed that whatever the 'name' variable was that was passed in will change after you set this up. Very frustrating! Also, some blog posts I have read say that if you want to change the onclick event handler you must declare the function like so:
var radioButton = document.getElementById('myRadioButton'); radioButton.onclick = function SayHi2(name);
This just does not work at all. It looks like will work but because you are dynamically changing the onclick event handler there is a high-possibility of your variables getting changed when your function executes. I think the reason is that JavaScript by nature is dynamic and anytime you change something that is dynamic you will get unexpected results. I am not sure why my variables changed unexpectedly but there is another way to set the function on the fly correctly. So, in the event that you are changing event handler this way you should do it following way:
var radioButton = document.getElementById('myRadioButton'); radioButton.onclick = new Function("SayHi2("'" + name + "'");");
This will call the Function() constructor which will build and assign a newly creately function to the radio button. This will make sure that your variables are not changed when your function executes. If you have any thoughts or comments, please post!
Josh
No comments:
Post a Comment