简体   繁体   中英

How jquery define click function for get parameter inside anonymous function?

I dont understand javascript syntax well,my question:

How jquery define click function for get parameter inside anonymous function?

The Case:

$("a").click(function(event) { 
    alert(event.type); 
});

in C the function should be defined:

void click(fn,event){
}

in javascript its looks to me that she defined as- (but where defined event?):

click (fn){

}

please explain to me the jquery syntax of click function code source here .

Thanks, Yosef

If you just want to find out where the event object is passed to your handler, that would be line 2568 of the jQuery-1.5.2 redistributable source code (or line 438 of the actual, un-contatenated source file ):

var ret = handleObj.handler.apply( this, args );

In the above line of code, handler is your anonymous function and args is an array whose first element is the event object. jQuery uses the apply method of the JavaScript Function object to invoke the handler and pass in the arguments

The jQuery source code is quite complex when it comes to full sequence of adding and handling events so, unless you want a line-by-line explanation of hundreds of lines of code, I suggest you rephrase your question to a smaller scope (eg You could create a toy demonstration of the scenario you want to understand).

Perhaps this will help?

dosomething(function(message) {
    alert(message);    
});

function dosomething(fn) {
    fn("Hello!");
}

The first part of the jQuery is the selector $("a") which selects and returns object(s) selected from the DOM. In this case, it will return a list of all anchor tag objects on the page.

Then, you are chaining the .click() method to that, jQuery attaches an event listener to all of the anchor tags. When the event listener is attached, it is more or less the equivalent of doing

<a href='..' onclick='someFunction(event)'>some link</a>

...which passes the event object to the function.

For example, compare to this:

<a onclick='blah(event)'>click</a>
<script type='text/javascript'>
function blah(e) {
  alert (e.type);
}
</script>

If I click on it, I will see "click" in the alert. In principle, jQuery is doing the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM