I'm trying to write a function that reads the oncontextmenu event for a div item. (I need it to find out whet开发者_开发问答her the ctrl key was being pressed, e.g. by using e.ctrlKey.)
This works:
<div id="item_2" class="lineitem" align=center oncontextmenu="alert('foo');">test</div>
But this does not:
<script language="JavaScript">
function asdf(e){
alert('foo');
}
</script>
<div id="item_2" class="lineitem" align=center oncontextmenu=asdf>test</div>
What do I need to do to fix the second one?
Thanks.
<div oncontextmenu="asdf(event)">
<script type="text/javascript">
function asdf(event){
if (event.ctrlKey)
alert('foo');
}
</script>
Why this works: inside the anonymous function created by an event handler attribute string, there is a local variable event
initialised to point to the Event instance. IE has a broken event model, but this code still works because the event
now refers not to a local variable but the window.event
global.
However you would generally want to avoid event handler attributes these days. Better to assign event handlers from script itself, eg.:
<div id="thing">
<script type="text/javascript">
document.getElementById('thing').oncontextmenu= function(event) {
if (event===undefined) event= window.event; // fix for IE
if (event.ctrlKey)
alert('foo');
};
</script>
Putting it in script also means your HTML stays validatable. (oncontextmenu
is an IE extension that won't be standardised until HTML5.)
You can also migrate the same function to addEventListener
, but note that IE doesn't support it so you need to sniff for the presence of addEventListener
and if missing use the IE-specific attachEvent
instead. If you don't need multiple handlers for the same event on the same object it is easier (and more compatible with ancient browser) to just use the old-school onevent
-style handlers instead.
Note that contextmenu
is an unreliable event. It isn't supported in all browsers, may be disabled or may always still bring up the browser's real context menu, and on a Mac a common way to get it is with Control-click, which may confuse your check for ctrlKey
. Plus of course there are accessibility issues. Use context menus in web applications as a shortcut feature only, not as an essential access method.
oncontextmenu="asdf()"
You can't assign predefined functions directly using attribute values. Only anonymous functions (where function () {
and }
are replaced with attribute="
and "
. This makes it rather difficult to trap the event object (maybe impossible, it isn't something I've ever felt the need to investigate).
If you want to assign the function directly, do it using JavaScript with attachEvent/addEventListener.
oncontextmenu="asdf()"
should work, doesn't it?
精彩评论