我需要在点击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不起作用?
任何帮助
答案 0 :(得分:7)
$(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
});
答案 1 :(得分:1)
因为你必须将它附加到事件,而不是$(obj)
event.preventDefault()
@Juan的回答是正确的(虽然我之前提前15秒回答),但我想通过对代码的一些更改来展示如何正确地做到这一点
$("a.clearField").click(loadclearSearchPopup);
function loadclearSearchPopup(e){
e.preventDefault();
// ... your code after preventing default action
}
loadclearSearchPopup()
click
代替on('click', ...)
,假设您的网页上没有很多具有完全相同功能的链接,并且您不太可能更改其内容请注意,您无法将参数传递给函数,但可以在其中处理它们
<强> FIDDLE 强>