【问题标题】:ReferenceError: event is not defined error in FirefoxReferenceError:Firefox 中的事件未定义错误
【发布时间】:2013-12-29 15:32:12
【问题描述】:

我为客户创建了一个页面,我最初在 Chrome 中工作,但忘记检查它是否在 Firefox 中工作。现在,我遇到了一个大问题,因为整个页面是基于一个在 Firefox 中不起作用的脚本。

它基于所有具有rel 的“链接”,从而导致隐藏和显示正确的页面。我不明白为什么这在 Firefox 中不起作用。

例如页面的 id 为 #menuPage#aboutPage 等等。所有链接都有这个代码:

<a class="menuOption" rel='#homePage' href="#">Velkommen</a> 

它在 Chrome 和 Safari 中完美运行。

代码如下:

$(document).ready(function(){

//Main Navigation


$('.menuOption').click(function(){

  event.preventDefault();
  var categories = $(this).attr('rel');
  $('.pages').hide();
  $(categories).fadeIn();


});

// HIDES and showes the right starting menu
    $('.all').hide();
    $('.pizza').show();


// Hides and shows using rel tags in the buttons    
    $('.menyCat').click(function(event){
        event.preventDefault();
        var categori = $(this).attr('rel');
        $('.all').hide();
        $(categori).fadeIn();
        $('html,body').scrollTo(0, categori);

    });


}); 

【问题讨论】:

标签: javascript jquery html firefox


【解决方案1】:

这是因为你忘记将event 传入click 函数:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

附带说明,eevent 更常用,因为 Event 在大多数浏览器中是一个全局变量。

【讨论】:

  • ... 当然,Firefox 除外!为参数使用名称“事件”并没有什么坏处,因为它不是保留字或任何东西。
  • 非常正确,我想我刚刚从 jQuery 中获取了e! @Pointy
【解决方案2】:

您错误地声明了(某些)事件处理程序:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

您需要“事件”作为处理程序的参数。 WebKit 遵循 IE 对“事件”使用全局符号的旧行为,但 Firefox 没有。当您使用 jQuery 时,该库会规范行为并确保您的事件处理程序被传递事件参数。

edit — 澄清:您必须提供 some 参数名称;使用event 可以明确您的意图,但您可以将其称为ecupcake 或其他任何名称。

还请注意,您可能应该使用从 jQuery 传入的参数而不是“本机”参数(在 Chrome、IE 和 Safari 中)的原因是该参数(参数)是本机事件对象的 jQuery 包装器.包装器用于规范跨浏览器的事件行为。如果你使用全球版本,你就不会明白。

【讨论】:

  • 非常感谢。 meteor.js 使用了很多事件变量。 function(){.... 没有传递事件仍然适用于 chrome 和 safari。但是 Firefox 会失败。
猜你喜欢
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2014-11-19
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
相关资源
最近更新 更多