简体   繁体   中英

Cannot read property 'preventDefault' of undefined in javascript error

In Console I got following error using e.preventDefault() method I used e as a function parameter

  function function1(e){
     e.preventDefault();
   } 

1533 Uncaught TypeError: Cannot read property 'preventDefault' of undefined.

Called function1 like

    <a href="#none" onclick="function1()">Click Me</a> 

You have to pass event in the used function:

function1(event); // where you called it 

For example:

    <a href="#none" onclick="function1(event)">Click Me</a>

Make sure you call this function within an event handler. Such as :

 $(document).click(function(event){
      function1(event);
 });

You are writing the function wrong. Suppose you are using function on a particular button click having id as 'clickBtn' then you need to write function like this.

$("#clickBtn").on("click", function(e){
     e.preventDefault();
});

I remove event from function and invoke function in this way:

<button class="btn btn-primary" runat="server" id="btnSave" type="submit"                                           
          onserverclick="btnSave_OnServerClick"  onclick="return 
          jsFunction();">Save</button>

In JavaScript:

function jsFunction() {
        alert('call');
        if ($('#form1').bootstrapValidator('validate').has('.has-error').length) {
            alert('SOMETHING WRONG');             
        } else {
            alert('EVERYTHING IS GOOD');
            __doPostBack('<%=btnSave.UniqueID%>', '');
          }
        return false;
    }

You failed to pass the event as a parameter in your in luck event in the html. So it should be written as the sample below:

<a href="#none" onclick="function1(event)">Click Me</a>

function function1(event){
 e.preventDefault();
} 

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