jquery: event: event. preventdefault ();e没有定义

时间:2021-01-28 23:59:25

hey i have a jquery function that is triggered on an anchor's onclick event the function is as follows:

嘿,我有一个jquery函数在锚点onclick事件上被触发函数如下:

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没有定义。

i want to cancel the default onclick event of the anchor link, any help would be appreciated.

我想取消锚点链接的默认onclick事件,如有任何帮助将不胜感激。

2 个解决方案

#1


15  

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();
    });

});

#2


0  

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。将您的脚本保存在外部文件中以保持清晰。

#1


15  

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();
    });

});

#2


0  

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。将您的脚本保存在外部文件中以保持清晰。