javascript jquery : 事件: event.preventDefault(); , e 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10826354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery : event : event.preventDefault(); , e is not defined
提问by Amyth
hey i have a jquery function that is triggered on an anchor's onclick event the function is as follows:
嘿,我有一个在锚点的 onclick 事件上触发的 jquery 函数,该函数如下:
function dropDown(subid, e) {
e.preventDefault();
var sub = '#' + subid;
// hide all submenus first
$('.subnav').css({'display' : 'none'});
//Show the Current Subnav
$(sub).css({'display' : 'block'});
}
this is how i am tring to trigger it :
这就是我想要触发它的方式:
<a href="#!" onclick="dropDown('sn_cities')" >Cities</a>
However i am getting this error: e is undefined
但是我收到此错误: e is undefined
i want to cancel the default onclick event of the anchor link, any help would be appreciated.
我想取消锚链接的默认 onclick 事件,任何帮助将不胜感激。
回答by nnnnnn
You're not passing the event object (or anything at all) to the e
parameter of the function. Try this:
您没有将事件对象(或任何东西)传递给e
函数的参数。试试这个:
onclick="dropDown('sn_cities',event);"
I'd be inclined to lose the inline JS altogether though:
不过,我倾向于完全丢失内联 JS:
<a href="#!" data-dropDown="sn_cities">Cities</a>
$(document).ready(function() {
$("a[data-dropDown]").click(function(e) {
e.preventDefault();
// hide all submenus first
$('.subnav').hide();
//Show the Current Subnav
$('#' + $(this).attr("data-dropDown")).show();
});
});
回答by ahren
function dropDown(subid) {
var sub = '#' + subid;
// hide all submenus first
$('.subnav').css({'display' : 'none'});
//Show the Current Subnav
$(sub).css({'display' : 'block'});
}
<a href="#!" onclick="dropDown('sn_cities'); return false;" >Cities</a>
As a side note. Inline-javascript is not recommended. Keep your scripts in an external file for clarity.
作为旁注。不推荐使用内联 javascript。为清楚起见,将脚本保存在外部文件中。