jQuery click函数何时需要一个“事件"? [英] When does jQuery click function need an 'event'?
问题描述
我有一个带有jquery的click函数,直到我添加了事件"(见下文),该函数才起作用.
I had a click function with jquery which didnt work until I added the 'event' (see below).
何时需要该事件?本文档确实使用它: http://api.jquery.com/click/
When is the event needed? This documentation doenst use it: http://api.jquery.com/click/
工作:
$(document).ready(function () {
$('#div a').click(function () {
event.preventDefault();
$('#menu,#wrapper').toggleClass('open');
});
})
作品:
$(document).ready(function () {
$('#div a').click(function (event) {
event.preventDefault();
$('#menu,#wrapper').toggleClass('open');
});
})
推荐答案
您链接到的文档明确指出click
函数是.这是此文档的摘录:
The documentation you link to precises that the click
function is a shortcut for bind with eventType being "click"
. Here's an extract of this documentation :
.bind(eventType [,eventData],handler(eventObject))
.bind( eventType [, eventData], handler(eventObject) )
bind函数的原型显示,您提供的回调handler
收到一个eventObject
,这是您的代码中发生的事件.
The prototype of the bind function shows that handler
, the callback you provide, receives an eventObject
, which is the event you have in your code.
此事件是jQuery包装的事件,具有您调用的函数preventDefault
.
This event is a jQuery wrapped event, having the function you call, preventDefault
.
所以这行
event.preventDefault();
需要定义事件.在函数的声明中编写function(event)
会声明一个局部变量事件,该事件的值将是jQuery给定的eventObject
之一.
needs the event to be defined. Writing function(event)
in the declaration of your function declares the local variable event whose value will be the one of the eventObject
given by jQuery.
或者,如果您不喜欢定义变量,则可以执行以下操作:
Alternatively, if you don't like defining variables, you could do this :
$(document).ready(function () {
$('#div a').click(function () {
$('#menu,#wrapper').toggleClass('open');
return false; // this prevents default handling and also stops propagation
});
})
这篇关于jQuery click函数何时需要一个“事件"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!