【问题标题】:jquery : event : event.preventDefault(); , e is not definedjquery : 事件 : event.preventDefault(); , e 未定义
【发布时间】:2012-05-31 01:24:38
【问题描述】:

嘿,我有一个在锚点的 onclick 事件上触发的 jquery 函数,函数如下:

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

这就是我想要触发它的方式:

<a href="#!" onclick="dropDown('sn_cities')" >Cities</a>

但是我收到了这个错误:e is undefined

我想取消锚链接的默认 onclick 事件,任何帮助将不胜感激。

【问题讨论】:

    标签: javascript jquery preventdefault


    【解决方案1】:

    您没有将事件对象(或任何东西)传递给函数的e 参数。试试这个:

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

    我倾向于完全失去内联 JS:

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

    【讨论】:

      【解决方案2】:
      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>
      

      作为旁注。不推荐使用内联javascript。为清楚起见,将脚本保存在外部文件中。

      【讨论】:

      • 感谢您的回复,现在试试,只是好奇,在jquery中不能通过事件传递其他参数吗?
      • 你可以,因为 nnnnnn 也发布了。
      • 他调用 preventDefault 来阻止锚点触发并跳转到“#”链接,您只需删除它?
      • return false; 相当于preventDefault();stopPropagation();
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      相关资源
      最近更新 更多