You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用oncontextmenu替代jQuery绑定右键事件时preventDefault报错求助

解决oncontextmenu属性调用函数时preventDefault()报错的问题

嘿,这个问题太常见啦!你碰到的Uncaught TypeError: Cannot read property 'preventDefault' of undefined错误,核心原因很简单——你通过oncontextmenu属性调用fn()的时候,没把事件对象传递给函数,函数里的e是undefined,调用它的方法自然会报错。

给你两个简单直接的解决办法:

方法一:在属性中直接传递事件对象(推荐)

这是最符合标准的写法,只需要修改HTML里的oncontextmenu属性,把event作为参数传进去就行:

<script>
function fn(e){ 
  e.preventDefault(); 
  console.log('lorem'); 
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent' oncontextmenu='fn(event)'>lorem</div>

这样函数里的e就能拿到右键点击的事件对象,preventDefault()会正常阻止默认右键菜单弹出,控制台也会顺利打印出'lorem'。

方法二:在函数中使用全局事件对象(兼容旧场景)

要是你不想在HTML里写event参数,也可以在函数里直接用window.event(现代浏览器和旧IE都支持),不过这种写法不如第一种规范:

<script>
function fn(){ 
  const e = window.event;
  e.preventDefault(); 
  console.log('lorem'); 
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent' oncontextmenu='fn()'>lorem</div>

两种方法都能解决你的问题,优先选第一种,它更贴合DOM事件的标准传递逻辑,可读性也更强。

内容的提问来源于stack exchange,提问作者qadenza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:31:16