【问题标题】:event.preventDefault() doesn't work in firefoxevent.preventDefault() 在 Firefox 中不起作用
【发布时间】:2016-06-13 22:07:00
【问题描述】:

我想使用 blow 功能来阻止像“a href”这样的默认操作,但它在 firefox 中无法正常工作。

function alertPopup(html) {
    event.preventDefault();
    // ...
}

然后我将变量“event”添加到这个函数中,作为打击,但也失败了; firefox 控制台显示错误“ReferenceError: event is not defined”。

function alertPopup(html) {

    function stepstop(event){
        console.log("tttttt");
        event.stopPropagation();
    };
    stepstop(event);
            // ...
}

<a href="#" onclick="alertPopup("hello");">XXXXX</a>

那么我怎样才能防止这个函数中的默认操作呢?不使用“return false”...谢谢!

【问题讨论】:

  • 您正在尝试停止全局事件对象,这不一定与正在处理的事件相同。请将您的代码添加到您调用alertPopup() 函数(可能是事件处理程序)的问题中
  • 你在哪里打电话stepstop
  • 如果未向事件处理程序提供事件参数,则会引发 Firefox 中事件的引用错误。谷歌不会抛出这个错误,它会准确地找到事件发起者。所以在调用 stepstop 函数时你没有传递事件对象
  • 好吧,您没有将事件传递给您的方法。方法是如何被调用的。
  • 在 Firefox 中事件不是全局窗口对象的属性。 how to access event object 上的现有问题可能能够回答您的问题。

标签: javascript jquery html firefox


【解决方案1】:

参加活动

function alertPopup(event, html) {
    event.preventDefault();
    console.log(html);
}
&lt;a href="#" onclick="alertPopup(event, 'hello');"&gt;XXXXX&lt;/a&gt;

更好的方法是使用 addEventListener() 附加事件,而不是使用内联事件。

【讨论】:

  • 在“onclick='alertPopup(event, 'hello');'”中有没有不加“event”的方法?
  • 如果你要使用内联事件,那就是你必须要做的。
【解决方案2】:

不要在锚标签上使用onclick属性,而是尝试在Javascript中添加一个事件监听器,这样你就可以在实际的点击事件上防止默认。

使用 JQuery,它看起来像这样:

$('a').on('click', function(e){
    e.preventDefault();
    ......
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多