简体   繁体   中英

Event prevent default

I have function below

function someName(e){
   e.preventDefault();
   $('#someCont').dialog({
     width:200,
     height:auto,
     modal:true
   })
}

And I am using it like

HTML

<a href="#" onclick="someName()">Link Name </a>

but in browser it throws an error "e is not defined". Can anybody suggest where I am doing wrong? the anchor tag could be more than 1

bind a click function via jquery rather than putting it inline

(function($){
    $(function() {
        function someName(e) {
            e.preventDefault();
        }

        $('a').click(function(e) {
            someName(e);
        });
    });
})(jQuery);

or add the parameter in the function:

onClick="someName(e)"

You need to pass event object

<a href="#" onclick="someName(event)">Link Name </a>

Alternative approach could be if you do not use inline event and assign some id or class to anchor and use that to bind event.

HTML

<a href="#" id="a1">Link Name </a>

Javascript

$('#a1').click(function(e){
  e.preventDefault();
   $('#someCont').dialog({
     width:200,
     height:auto,
     modal:true
   })
});

In function someName(e) , e is an event object. So whenever you are calling this function, you should pass window event object an argument like given below:

<a href="#" onclick="someName(event)">Link Name </a> // Here I have passed this object 

Otherwise, you'll get the same error 'e not defined'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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