简体   繁体   中英

How to pass the event argument of jQuery .click() to a non-anonymous function

What is the proper way to accomplish the following:

$("#btn").click(function1);

Calling the function:

function function1 (event) {
    event.preventDefault();
}

This seems to work, however I don't understand how function1 understands what the event argument is referring to without it being passed in. Wouldn't a listener set up like this make more sense:

$("#btn").click(function1(event));

Here is a fiddle .

The .click() function in jQuery except as first parameter a function. In Javascript function are value, as well as a primitive value or an object. Functions are first-class citizens .

If you use function1(event) as a parameter, the function will be executed, because this is the semantic of the brachet after the function name. So the .click() jQuery function will receive the output of the function, which is not the expected type.

Passing the function name as a parameter means that you are passing the function (actually, a reference to the function), not the result of the function invocation. And the function will be called when the click event will be triggered. The function in this case is called " callback ".

Callbacks are very importants in Javascript, since the event-driven behaviour is the main reason for using a client-side scripting.

The concept behind the callback system is

//the click function
function doSomething(callback){
//in your case the event is the argument that jQuery will prepare for you
var argument = produceTheArgument();
//doSomething is in charge to invoke the function, passing the argument
callback(argument);
}

//your function
function myCallback(argument){
 //your function will consume the argument
}

//my callback is passed as a reference, not invoked
doSomething(myCallback);

您正在订阅事件,并在点击侦听器中传递对该函数的引用-jQuery事件处理器将仅在jQuery的上下文中调用您的函数,并将所有参数传递给该函数。

In your first example function1 knows that the event variable is, because JavaScript (and subsequently jQuery) passes the event information as a parameter.

This is the nature of JavaScript, not just jQuery. Consider the following:

document.getElementById('btn').addEventListener('click', function1, false);

function function1(e)
{
    console.log(e);
}

JavaScript automatically calls function1 when #btn is clicked, and it automatically adds the event information as the first parameter. jQuery simply passes this information into its own methods as well, so that you have access to it.

According to jQuery's documentation:

The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.

Reference: http://api.jquery.com/click/

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