【问题标题】:PreventDefault give a TypeError [duplicate]PreventDefault 给出一个 TypeError [重复]
【发布时间】:2015-11-06 10:11:25
【问题描述】:

这是我的代码行:

var $hotlinePanel = $('#hotlines-panel');
var $hotlineTile = $('#redirects-tile-6 .redirect-overlay');

$hotlineTile.on('click', togglePanel(event));

function togglePanel(event){
    event.preventDefault();
    $hotlinePanel.toggleClass('open');
};

这是控制台的错误:

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

我做错了什么?

【问题讨论】:

  • 回答: 更改 $hotlineTile.on('click', togglePanel(event)); ==> $hotlineTile.on('click', togglePanel);。解释见jquery :: Why does hover trigger instantly?
  • 欢迎您!乐意效劳。请不要打电话给先生

标签: jquery event-handling jquery-events preventdefault


【解决方案1】:

只需稍作改动如下:

$hotlineTile.on('click', togglePanel);  // remove-(event), call function with name only - function declaration

// function defination

function togglePanel(e){
    e.preventDefaut();
    $hotlinePanel.toggleClass('open');
};


更新:

注意:preventDefault() 方法不会阻止事件通过 DOM 传播。使用stopPropagation() 方法来处理。

【讨论】:

  • 天哪,谢谢。如果我想在该函数中阻止来自 Dom 中其他对象的默认事件,我该怎么办?
  • 您介意解释一下为什么/如何这可能/将起作用吗?
  • @Tushar 先生,在第一行 togglePanel 是一个函数的声明,然后我们定义函数体。 (我是jquery的学习者,如果有错误请纠正我)谢谢
  • 好的,在答案中添加这个。不要打电话给sir
猜你喜欢
  • 2013-07-07
  • 2021-10-15
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多