【问题标题】:Both event.preventDefault() and event.returnValue = false don't work in Firefoxevent.preventDefault() 和 event.returnValue = false 在 Firefox 中都不起作用
【发布时间】:2013-07-18 00:59:50
【问题描述】:

我已经尝试过这些对代码的 sn-ps,第一个在 IE 和 Chrome 中工作,第二个只在 Chrome 中工作,但它们都不能在 Firefox 中工作。我想要的是阻止页面通过链接转到其他页面

$('.album a').click(function(){
    event.returnValue = false;
    //other codes
})

$('.album a').click(function(){
    event.preventDefault();
    //other codes
})

编辑: Ian 的这个 sn-p 对我有用

$('.album a').click(function(e){
    e.preventDefault();
    //other codes
});

【问题讨论】:

  • 您可能会考虑不使用链接,尤其是当您没有将它们用作链接时。您可以使用另一个元素(span 等),如果您愿意,可以使用 css 使其看起来像一个链接。

标签: javascript firefox return-value preventdefault


【解决方案1】:

您需要提供Event参数:

$('.album a').click(function(e){
    e.preventDefault();
    //other codes
});

您不需要处理 returnValue,因为 jQuery 仅通过调用 preventDefault 即可将该方法标准化为跨浏览器工作。

请注意文档中的处理程序如何将此 eventObject 显示为传递给它的参数:http://api.jquery.com/click/

并注意Event 对象如何具有preventDefault 方法:http://api.jquery.com/category/events/event-object/

【讨论】:

    【解决方案2】:

    您的回调签名未注册 event 参数。因此,您的回调无法访问 event 对象,也无法阻止它。

    $('.album a').click(function(event){
        event.returnValue = false;
        //other codes
    });
    
    $('.album a').click(function(event){
        event.preventDefault();
        //other codes
    });
    

    【讨论】:

      【解决方案3】:

      尝试将您的代码更改为以下内容:

      $('.album a').click(function(e){
          e.preventDefault();
          return false;
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-02
        • 2015-03-05
        • 2016-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-12
        相关资源
        最近更新 更多