event.returnValue和return false的区别

本文深入解析JavaScript中事件控制的关键概念,如event.returnValue与return false的区别,以及如何利用这些概念进行有效的表单验证和事件处理。通过实例展示了如何阻止默认事件行为,并解释了return true/false在不同上下文中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先:概念如下:

event.returnValue的作用就是:

当捕捉到事件(event)时,做某些判断,如果判断失败,则阻止当前事件继续运行,这样讲您也许还不是特别理解,我再举一个例子,该例子达到的效果是:不能在一个输入框中输入小数。

return false的作用就是:返回一个false值;

在一些用return false;禁止一些浏览器的默认行为的时候,由于原先默认的行为是ture,例如,<a>链接,点击事件发生后,紧接着的默认事件就是跳转链接,但是,在onclick=function(){return false;}之后,就可以对紧接着的默认时间进行禁止掉;


这个event.returnValue与return false的区别是,在实战中,对表单验证而言,event.returnValue=fasle和return function(){return false}的效果是一样的,都是先对表单的内容进行判断,才决定是否执行下去,但是,这个return function(){return false}和function(){return false}又是有区别的,前者是在先对函数的内容的判断上是否执行下去的,但是,后者则不会进行判断就直接执行下去了


注意:onclick=""事件相当于 onclick=return true/false  ,此时不管function ok(){return false}   ,在onclick="ok()",都是直接返回ture的,所以,它依旧是默认执行下去。


下面补上经典案例分析:

这里面的return含有一些细节知识:

例如:onClick='return add_onclick()'与 onClick='add_onclick()'的区别

JAVASCRIPT在事件中调用函数时用return返回值实际上是对window.event.returnvalue进行设置。

而该值决定了当前操作是否继续。
当返回的是true时,将继续操作。
当返回是false时,将中断操作。

而直接执行时(不用return)。将不会对window.event.returnvalue进行设置
所以会默认地继续执行操作

详细说明如下:
例如:
当在 <a href="abc.htm" onclick="return add_onclick()">Open</a> 中
如果函数 add_onclick() 返回 true, 那么 页面就会打开 abc.htm
否则, (返回 false), 那么页面不会跳转到 abc.htm, 只会执行你的 add_onclick() 函数里的内容. (add_onclick函数中控制页面转到 abc.htm除外

)
而 <a href="abc.htm" onclick="add_onclick()">Open</a>
不管 add_onclick() 返回什么值, 都会在执行完 add_onclick 后打开页面 abc.htm

另外补充:
onclick事件时就相当于onclick="return true/false"
例:
function check()
{
if(obj.value=="" )
   {
     window.alert("不能为空!");
     obj.focus();
     return false;
   }
     return true;
}

调用方法返回true时才提交表单,反之则不提交,这是submit按钮
------------------------------------------------------------------------------------------

调用js函数不需要return,但是表单却无法提交,所以在js函数中加上一句话
例:
<script language="javascript">
function check()
{
if(obj.value=="" )
   {
     window.alert("不能为空!");
     obj.focus();
     return false;
   }
     document.myform.submit();
     return true;
}
</script>
注:document.myform.submit();要在return true前

 

 

关于javascript中的 return false和return true
return 是javascript里函数返回值的关键字,
一个函数内处理的结果可以使用return 返回,
这样在调用函数的地方就可以用变量接收返回
结果。return 关键字内任何类型的变量数据或表达式
都可以进行返回,甚至什么都不返回也可以比如
function NullReturn(IsNull)
{
if(IsNull==true)
{
return;
}
}
这样写也是可以的,这里的意思是返回空(null)
所以有的时候return 的作用就是用来终止函数执行。
比如
<html>
<head>
<title>return验证测试</title>
<script language="javascript">
function Login_Click()
{
if(document.form1.UsName.value=="")
{
alert('用户名为空');
}
if(document.form1.UsPwd.value=="")
{
alert('密码为空');
}
alert('登陆成功');
}
</script>
</head>
<body>
<form name="form1">
<input type="text" name="UsName" >用户名
<input type="password" name="UsPwd">密码
<input type="button" name="Login" onClick="Login_Click();" >登陆
</form>
</body>
</html>
不加return 的情况
加return
<html>
<head>
<title>return验证测试</title>
<script language="javascript">
function Login_Click()
{
if(document.form1.UsName.value=="")
{
alert('用户名为空');
return;
}
if(document.form1.UsPwd.value=="")
{
alert('密码为空');
return;
}
alert('登陆成功');
}
</script>
</head>
<body>
<form name="form1">
<input type="text" name="UsName" >用户名
<input type="password" name="UsPwd">密码
<input type="button" name="Login" onClick="Login_Click();" >登陆
</form>
</body>
</html>

运行就会发现加return 和不加return 的区别,
最简单的测试办法,上面的两个例子什么都不输入直接登陆

不加return的现象是先提示用户名没输入,然后提示密码没输入;加了return之后遇到一个没输入之后就不再继续检测

return false表示返回一个false值,也就是说提交是不成功的,就是不会提交上去。
return true表法返回一个true值,也就是提交了,不管你输入没有输入值,都会提交到action指定页面。


// useHandleEvent.js import { ref, onMounted, onUnmounted } from "vue" interface EventType { type: "click" | "dblclick" | "longclick" cell: { row: number; col: number; element: any } originalEvent: MouseEvent | TouchEvent | any } export function useHandleEvent(containerRef: Ref<HTMLElement>, callback: (cb: EventType) => void) { const touchInfo = ref<{ startX: number startY: number startTime: number target: any } | null>(null) const isMobile = ref(false) const lastClickInfo = ref({ time: 0, target: null as any }) const longPressTimer = ref<NodeJS.Timeout | null>(null) const isLongPress = ref(false) const detectMobile = () => { return ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1) ) } // 获取事件单元格信息 const getCellFromEvent = (event: any) => { if (!event) return null let target = event.target while (target && target !== containerRef.value) { if (target.dataset?.row !== undefined && target.dataset?.col !== undefined) { return { row: parseInt(target.dataset.row), col: parseInt(target.dataset.col), element: target } } target = target.parentNode } return null } // 触发回调的统一方法 const triggerCallback = (type: "click" | "dblclick" | "longclick", cell: any, event: any) => { const resData = { type, cell, originalEvent: event } return callback(resData) } // 处理鼠标按下事件 const handleMouseDown = (event: MouseEvent) => { // 阻止右键菜单 if (event.button === 2 || event.button === 3) { event.preventDefault() return } const cell = getCellFromEvent(event) if (!cell) return // 设置长按定时器 longPressTimer.value = setTimeout(() => { isLongPress.value = true triggerCallback("longclick", cell, event) }, 500) } // 处理鼠标抬起事件 const handleMouseUp = (event: MouseEvent) => { if (longPressTimer.value) { clearTimeout(longPressTimer.value) longPressTimer.value = null } if (isLongPress.value) { isLongPress.value = false return } const cell = getCellFromEvent(event) if (!cell) return const now = Date.now() if (lastClickInfo.value.target === cell && now - lastClickInfo.value.time < 300) { triggerCallback("dblclick", cell, event) lastClickInfo.value = { time: 0, target: null } } else { triggerCallback("click", cell, event) lastClickInfo.value = { time: now, target: cell } } } // 处理触摸开始事件 const handleTouchStart = (event: TouchEvent) => { if (event.touches.length > 1) return const touch = event.touches[0] const cell = getCellFromEvent(event) if (!cell) return touchInfo.value = { startX: touch.clientX, startY: touch.clientY, startTime: Date.now(), target: cell } longPressTimer.value = setTimeout(() => { event.preventDefault() isLongPress.value = true triggerCallback("longclick", cell, event) }, 500) } // 处理触摸结束事件 const handleTouchEnd = (event: TouchEvent) => { if (longPressTimer.value) { clearTimeout(longPressTimer.value) longPressTimer.value = null } if (!touchInfo.value) return if (isLongPress.value) { isLongPress.value = false touchInfo.value = null return } const touch = event.changedTouches[0] const cell = getCellFromEvent(touch) if (!cell || cell !== touchInfo.value.target) { touchInfo.value = null return } const moveDistance = Math.sqrt( Math.pow(touch.clientX - touchInfo.value.startX, 2) + Math.pow(touch.clientY - touchInfo.value.startY, 2) ) if (moveDistance < 10) { const now = Date.now() if (lastClickInfo.value.target === cell && now - lastClickInfo.value.time < 300) { triggerCallback("dblclick", cell, event) lastClickInfo.value = { time: 0, target: null } } else { triggerCallback("click", cell, event) lastClickInfo.value = { time: now, target: cell } } } touchInfo.value = null } // 阻止默认的右键菜单行为 const handleContextMenu = (event: MouseEvent) => { event.preventDefault() } // 鼠标移出时清除长按状态 const handleMouseLeave = () => { if (longPressTimer.value) { clearTimeout(longPressTimer.value) longPressTimer.value = null } isLongPress.value = false } onMounted(() => { if (!containerRef.value) return isMobile.value = detectMobile() containerRef.value.addEventListener("mousedown", handleMouseDown) containerRef.value.addEventListener("mouseup", handleMouseUp) containerRef.value.addEventListener("mouseleave", handleMouseLeave) containerRef.value.addEventListener("contextmenu", handleContextMenu) containerRef.value.addEventListener("touchstart", handleTouchStart, { passive: true }) containerRef.value.addEventListener("touchend", handleTouchEnd, { passive: true }) }) onUnmounted(() => { if (!containerRef.value) return containerRef.value.removeEventListener("mousedown", handleMouseDown) containerRef.value.removeEventListener("mouseup", handleMouseUp) containerRef.value.removeEventListener("mouseleave", handleMouseLeave) containerRef.value.removeEventListener("contextmenu", handleContextMenu) containerRef.value.removeEventListener("touchstart", handleTouchStart) containerRef.value.removeEventListener("touchend", handleTouchEnd) if (longPressTimer.value) clearTimeout(longPressTimer.value) }) return { isMobile } } 请根据这段代码进行优化,在PC端移动端统一都只返回按下down,弹起up,单击click,双击dblclick长按longclick 5种事件,其他的都阻止屏蔽,请确保能准确区分识别单击,双击长按事件
最新发布
08-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值