最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery : event : event.preventDefault(); , e is not defined - Stack Overflow

programmeradmin2浏览0评论

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

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

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

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

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

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

Share Improve this question edited May 31, 2012 at 1:31 apsillers 116k18 gold badges247 silver badges247 bronze badges asked May 31, 2012 at 1:24 AmythAmyth 32.9k27 gold badges96 silver badges136 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

You're not passing the event object (or anything at all) to the e parameter of the function. Try this:

onclick="dropDown('sn_cities',event);"

I'd be inclined to lose the inline JS altogether though:

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

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

发布评论

评论列表(0)

  1. 暂无评论