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

jQuery中如何借助e.preventDefault等方法根据函数返回值终止当前执行逻辑

实现方案

你当前的场景不需要使用e.preventDefault(),该方法仅用于阻止DOM元素的默认行为(如a标签跳转、表单提交)。要终止点击事件回调的后续代码执行,只需接收websControlYear()的返回值做判断,不满足条件时调用return即可,该关键字会直接终止当前所在函数的运行。

修改后的完整代码如下:

function websControlYear(){
    var year = 2020;
    if(year == 2020){
         return true;
    }else{
         return false;
    }
}

$("#div").click(function(e){
     const checkResult = websControlYear();
     if(!checkResult){
         alert("wrong value");
         // return 会直接终止当前点击函数的执行,后续代码不会运行
         return;
         // 若你需要同时阻止当前点击元素的默认行为,可取消注释下方代码
         // e.preventDefault();
     }
     // 此处编写校验通过后需要执行的后续逻辑
     console.log("校验通过,正常执行业务代码");
});

也可以简化判断逻辑,代码更简洁:

$("#div").click(function(){
     if(!websControlYear()) return alert("wrong value");
     // 后续业务代码
});

内容的提问来源于stack exchange,提问作者Jakub Halamík

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:24:05