5

From http://api.jquery.com/on/:

.on( events [, selector ] [, data ], handler(eventObject) )

I know this might sound a little stupid, but could anyone explain the syntax here?

What does the [] mean? I would think it means that you could add several options (selectors/data) but as you can also add several events, why does events not have square brackets?

Also here's an example .on():

    $(document).on("click", ".item", function() {
alert("hi");
});

Where does the data written in the method syntax come into play here?

1
  • 1
    I believe they are optional, events is required. Commented Apr 26, 2013 at 11:09

3 Answers 3

2

The square brackets indicate that an argument is optional. For the .on() method, both selector and data are optional, but events and handler are required.

For example:

$(something).on("click", function () {});
//                 ^ events    ^ handler

$(something).on("click", ".child", function () {});
//                ^ events   ^ selector   ^ handler

$(something).on(function () {}); // Won't work, missing events argument
Sign up to request clarification or add additional context in comments.

Comments

1

The [] indicate those parameters are optional. You can have zero or one selectors and data.

The example call omits the data parameter.

Comments

0

The square brackets indicate that the parameter is optional. So you can optionally provide a selector (for event delegation) or data (for use inside the event handler function), but you don't have to.

With regard to your specific example, there isn't any value being passed to data (because you don't have to do so). In the code for the jQuery on function it determines which parameter the value is actually for based on the type of the value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.