jQuery multiple events to trigger the same function

后端 未结 11 1098
青春惊慌失措
青春惊慌失措 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:34

    The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

    I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

    • 2.0.2
    • 1.10.1
    • 1.6.4
    • Mobile 1.3.0b1
    • Mobile 1.4.2
    • Mobile 1.2.0

    My workaround have been to first define the function,

    function myFunction() {
        ...
    }
    

    and then handle the events individually

    // Call individually due to IE not handling binds properly
    $(window).on("scroll", myFunction);
    $(window).on("resize", myFunction);
    

    This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue

提交回复
热议问题