简体   繁体   English

事件阻止默认

[英]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 的HTML

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

but in browser it throws an error "e is not defined". 但在浏览器中会引发错误“未定义e”。 Can anybody suggest where I am doing wrong? 有人可以建议我做错了什么吗? the anchor tag could be more than 1 锚标记可能会超过1

bind a click function via jquery rather than putting it inline 通过jquery绑定单击函数,而不是将其内联

(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. 如果您不使用内联事件并分配一些ID或类来锚定并使用它来绑定事件,则可以采用其他方法。

HTML 的HTML

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

Javascript Java脚本

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

In function someName(e) , e is an event object. function someName(e) ,e是事件对象。 So whenever you are calling this function, you should pass window event object an argument like given below: 因此,无论何时调用此函数,都应该向window事件对象传递一个如下所示的参数:

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

Otherwise, you'll get the same error 'e not defined' 否则,您将得到相同的错误'e not defined'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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