简体   繁体   中英

how to use multiple elements, multiple events, but same function in an if statement

Let's say I have:

if (event X happens on element A) execute Code R

if (event Y happens on element B) execute Code R

In jQuery, instead of the 2 if statements, how do you have 1 if statement whereby:

if (event X happens on element A) OR (event Y happens on element B) execute Code R

I've been looking at bind methods but haven't been able to find the solution to this. It's like Google's search function: If you click on the 'search' button, it executes the search. However, if you type something in the input box and press the 'enter' key, it also executes the search. Again, two different elements (button and input box), two different events (mouse click and key press), but same function (search)?

There won't be any if statements in your final code. You have to bind the event handler for each event to each element, and the event handler can of course be the same function:

function event_handler() {
    // ...
}

$(elementA).on('eventX', event_handler);
$(elementB).on('eventY', event_handler);

I recommend to read the jQuery tutorials: http://docs.jquery.com/Tutorials .

To learn more about event handling in general, have a look at these articles: http://www.quirksmode.org/js/introevents.html .

You'll need to add the same function to both event / element combinations:

$('#elementA').on('click', myEventHandler);
// You can specify multiple Events:
$('#elementB').on('mousedown mouseup blur', myEventHandler);
// Or specify multiple elements:
$('#elementB, #elementC').on('click', myEventHandler);

function myEventHandler(e){
    console.log(e.type); // Event type ('mousedown', 'mouseup' etc)
    console.log(this);  // The element that triggered the event.
    // Do stuff.
}

But you can't bind click to '#elementA' and mousedown to '#elementB' in 1 line.

So, no, there is no "One-liner" jQuery function to bind multiple different events to different elements.

Basically, Have a look at jQuery's .on()

You can use multiple jQuery selectors separated by commas (like CSS selectors). The resulting jQuery object list will contain all of them.

Binding multiple events in jQuery is allowed if you use .bind() or .on() and set the first parameter to be a list of event names separated by spaces.

function handler_function (e) {
    e.target // contains the element that triggered the event (which was clicked for ex.)
    e.type // contains the event type that triggered the event
    e.keyCode // contains a number representing the key that has been pressed (if any)
}
$('button#button_id, input[type=text]#input_box')
    .bind('keyup click hover touch drag drop', handler_function);

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