jQuery multiple events to trigger the same function

后端 未结 11 1075
青春惊慌失措
青春惊慌失措 2020-11-22 04:45

Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do the

相关标签:
11条回答
  • 2020-11-22 05:37

    You could define the function that you would like to reuse as below:

    var foo = function() {...}
    

    And later you can set however many event listeners you want on your object to trigger that function using on('event') leaving a space in between as shown below:

    $('#selector').on('keyup keypress blur change paste cut', foo);
    
    0 讨论(0)
  • 2020-11-22 05:42

    Is there a way to have keyup, keypress, blur, and change events call the same function in one line?

    It's possible using .on(), which accepts the following structure: .on( events [, selector ] [, data ], handler ), so you can pass multiple events to this method. In your case it should look like this:

    $('#target').on('keyup keypress blur change', function(e) {
        // "e" is an event, you can detect the type of event using "e.type"
    });
    

    And here is the live example:

    $('#target').on('keyup keypress blur change', function(e) {
      console.log(`"${e.type.toUpperCase()}" event happened`)
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="target">

    0 讨论(0)
  • 2020-11-22 05:43
    $("element").on("event1 event2 event..n", function() {
       //execution
    });
    

    This tutorial is about handling multiple events.

    0 讨论(0)
  • 2020-11-22 05:44

    It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:

    function validate() {
      // ...
    }
    
    const element = document.querySelector('#element');
    ['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
      element.addEventListener(eventName, validate);
    });
    
    0 讨论(0)
  • 2020-11-22 05:47

    As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

    $(document).on('mouseover mouseout',".brand", function () {
      $(".star").toggleClass("hovered");
    })
    
    0 讨论(0)
提交回复
热议问题