繁体   English   中英

锚链接不适用于jquery event.preventDefault;

[英]anchor link not working with jquery event.preventDefault;

我需要在使用jQuery的锚链接单击时打开弹出窗口。

这是HTML部分

<a href="/waw/jvcc/customerSearch.htm" title="Clear Search" class="clearField" id="clearText">Clear Search</a>

这是jQuery

$("a.clearField").on("click", function(){loadclearSearchPopup()});

function loadclearSearchPopup(obj){
    var delay = '';

    $(obj).preventDefault;
    //popup open code goes here;
    return false;
} 

我知道我可以通过用href =“#”替换href来变通,但是我很好奇为什么event.preventDefault并返回false不能正常工作?

任何帮助

$(obj).preventDefault;

应该

e.preventDefault();

这是事件的方法,而不是jQuery对象的属性。 另外, return false无效的原因是因为您没有将返回值传递回处理程序

$("a.clearField").on("click", function (e){
    var delay = '';
    // Prevents the link from being followed
    e.preventDefault();
    // Prevents following links and propagation (bubbling the event)
    // Note that this is a jQuery feature only. In standard DOM event handlers,
    // return false is the same as e.preventDefault()
    return false;
    // But you don't need both
});

因为您必须将其附加到事件,而不是$(obj)

event.preventDefault()

@Juan的答案是正确的(尽管我早于15秒回答了),但我想展示如何通过对他的代码进行一些更改来正确地做到这一点

$("a.clearField").click(loadclearSearchPopup);

function loadclearSearchPopup(e){
    e.preventDefault();
    // ... your code after preventing default action
}
  1. 就您在loadclearSearchPopup()拥有的所有代码而言,我没有使用匿名函数
  2. 我使用click代替on('click', ...)假设您的页面上没有很多功能完全相同的链接,并且您不太可能更改其内容
  3. 我阻止对第一个字符串执行操作,因为也许以后您将需要返回一些结果或将其破坏,并且阻止对最后一个字符串执行不会

请注意,您不能将参数传递给函数,但可以在其中处理参数

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM