I would move my former js codes to more OOP style. Here's the code.
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
function test() {
}
test.prototype = {
init: function () {
addEvent(document, 'mousedown', this.displaydown);
},
displaydown : function(e){
document.getElementById('mydiv').innerHTML = "down";
addEvent(document, 'mousemove', this.displaymove);
},
displaymove : function(e){
document.getElementById('mydiv').innerHTML = "move";
}
}
var test0 = new test();
test0.init()
I could not add mousemove event after mousedown with
addEvent(document, 'mousemove', this.displaymove);
But if I write inline style like
addEvent(document, 'mousemove', function(e){
document.getElementById('mydiv').innerHTML = "move";
});
It's OK. It looks the 2 codes do the same thing. Why is there the difference? Thanks!
edit,
After struggle for 2 nights I finally solved the problem. Thanks johnvey for your enlighting.
The erro occurs on this keyword. In the event of an object, this refers to window rather than object itself. The solution is I defined global parameter me (me = this) at the beginning. Now it's OK.