ReferenceError: 在 Firefox 中没有定义事件错误

我为一个客户制作了一个页面,最初我使用的是 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);


});




});
147033 次浏览

You're declaring (some of) your event handlers incorrectly:

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


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




});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

It is because you forgot to pass in event into the click function:

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


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


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

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.