You can do it more simple:
var clicker = document.getElementById("click");
clicker.onclick = do_this;
function do_this (){
alert("this");
clicker.onclick = do_that;
}
function do_that (){
alert("that");
clicker.onclick = do_this;
}
Вопрос
Why isn't the two phases shifting in the fiddle: http://jsfiddle.net/WH7Kf/43/
function phase_switch(){
var phase;
clicker = document.getElementById("click");
phase=1
switch (phase) {
case 1:
clicker.onclick = do_this;
break;
case 2:
clicker.onclick = do_that;
break;
}
function do_this (){
alert("this");
phase==2;
}
function do_that (){
alert("that");
phase==1;
}
}
window.addEventListener("load", phase_switch());
As you can probably tell Phase one is the only phase that's firing. Why isn't phase 2 firing?
Решение
You can do it more simple:
var clicker = document.getElementById("click");
clicker.onclick = do_this;
function do_this (){
alert("this");
clicker.onclick = do_that;
}
function do_that (){
alert("that");
clicker.onclick = do_this;
}
Другие советы
You have a few syntax issues, from the beginning:
1) The fiddle is already setup to execute JavaScript code onLoad
; check the sidebar for different options.
2) You're missing variable declarations. When you omit var
the variable becomes global and it's accessible outside the function; you don't want this.
3) =
is assignment, ==
is equality, ===
is strict equality. Look up the MDN for more info
4) I think you're over-complicating things. Try to separate concerns. Make a function that expects an element and messages, and do the logic inside the event handler. You can keep track of a flag to switch between two different messages, stored in an array. For example:
var clicker = document.getElementById("click");
/**
* @param el DOM element
* @param msgs Array containing 2 messages
*/
function phaseSwitch(el, msgs) {
var flag = false;
el.addEventListener('click', function() {
alert(msgs[+flag]); // casts flag to index (0|1)
flag = !flag; // invert flag
});
}
phaseSwitch(clicker, ['hello', 'bye']);
Window load event occurs once in page life cycle, you are binding click handler in window load event which will gonna execute once. so phase
will have value as 1 at the first time hence when you click on button do_this
will execute always