开发者

What is the "event" parameter that so often is defined for JavaScript event handler functions?

A lot of time I see jQuery code that looks like this:

$('a').live( 'click', function(event){
..
});

What does the event parameter do? Does it correspond 开发者_如何学JAVAto the element 'a' or the event 'live'?


It means that every anchor element on the page (a) as well as any dynamically added anchor elements in the future will have a click event attached to them that will run whatever the function is passed in.

jQuery documentation of the live method

the parameter event of the function that is passed in is the result of a click on an anchor element. If you are using Firefox with Firebug you can examine this object by doing this:

$("a").live("click", function(event) { 
    console.dir(event);
});

When you click on an anchor you will then be able to see the whole object in the Firebug console.


I think you were asking specifically about what an event is and not necessarily the live function. event is a jQuery.Event (http://docs.jquery.com/Events/jQuery.Event) object which holds numerous things about the event including a reference to the clicked object.


event is, in this case, associated with the 'click' event that happens on every a tag in the HTML. It is an object that holds all the associated properties of the mouse click.

live is more effective than just binding an event, because it will attach itself to any a tags dynamically created after all of the event binding is done.


In javascript (not just specific to jQuery) the event object is an object that describes the event that just happened. W3C DOM standards specifies that the event object is the first parameter passed to an event handler. On IE, the event object is a global variable instead. So in regular javascript (without libraries like jQuery) you'll often find people write things like:

div.onclick = function (event) {
  event = event || window.event; // take care of IE
  ..
}

Most libraries like jQuery take care of this for you so you only need to do the W3C standard thing.

The event object is the only standard mechanism of finding out things like mouse pointer xy location, which key is pressed etc.

see: https://developer.mozilla.org/En/DOM:event

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜