Javascript 无法读取javascript错误中未定义的属性“preventDefault”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38260064/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:15:15  来源:igfitidea点击:

Cannot read property 'preventDefault' of undefined in javascript error

javascriptjquery

提问by Jai

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

在控制台中,我使用 e.preventDefault() 方法出现以下错误,我将 e 用作函数参数

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

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

1533 未捕获的类型错误:无法读取未定义的属性“preventDefault”。

Called function1 like

调用 function1 就像

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

采纳答案by Kehdcode

i remove event from function and invoke function in this way

我以这种方式从函数中删除事件并调用函数

onserverclick="btnSave_OnServerClick" onclick="return jsFunction();">Save

onserverclick="btnSave_OnServerClick" onclick="return jsFunction();">保存

In javascript

在 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;
    }

回答by Jai

You have to pass eventin the used function:

您必须传入event使用的函数:

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

回答by Laxminarayan

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.

你写的函数错了。假设您在特定按钮单击上使用函数,其 id 为“clickBtn”,那么您需要编写这样的函数。

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

回答by Kehdcode

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:

您未能在 html 中的幸运事件中将该事件作为参数传递。所以它应该写成下面的示例:

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

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