jQuery multiple events to trigger the same function

后端 未结 11 1291
青春惊慌失措
青春惊慌失措 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: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`)
    });
    
    

提交回复
热议问题