问题
I am displaying context menu on right-clicking a button in a page. The code used for displaying context menu is
window.addEventListener('contextmenu',function (e){e.preventDefault();},false);}
When I am right clicking the button, the context menu method called is
displaycontextmenu(obj,event)
{
console.log("Context");
console.log(event);
// Displaying context menu
}
The code executes fine in IE browser, even in chrome I can see in console that "Context" and event is printed. But in firefox , it is printing as "Context" and undefined. I am really confused to see here that the event is undefined.
I am using the event to get the x and y co-ordinates to display the context menu at right place. Since the event is undefined, am not able to proceed further.
回答1:
The reason why you can see the event show up in the console of chrome and IE is that IE has always had the bad habbit of assigning the event object to a global reference (window.event).
Chrome has implemented the W3C model correctly, and passes the event object to the handler as you'd expect, but also keeps a global reference to that event object ready, just in case.
Try logging obj, it'll log the event object in FF... I'm fairly confident of that. Chrome will behave in exactly the same manner, too: the event object will be passed to the handler.
Since the event parameter is left undefined, I can only assume that event is either ignored (treated as a reserved keyword, but only quietly), or there is some behind-the-scenes scope-scanning going on that resolves the local event to the global [window.]event.
At any rate, using varnames that might be keywords, or that already exist (like document, window or this) is either not allowed or frowned upon. That's why you'll often see this:
function eventHandler (e)
{
e = e || event;
}
e is allowed as a varname, and there is no name conflict, unless we ourselves create one. if the handler didn't receive an event object, we reference event which, thanks to scope scanning, will be resolved to window.event.
来源:https://stackoverflow.com/questions/16044100/event-is-undefined-for-firefox-browser-on-calling-oncontextmenu