jQuery 1.9 .live() is not a function

前端 未结 10 1062
再見小時候
再見小時候 2020-11-22 03:46

I recently updated jQuery from 1.8 to 2.1. I suddenly discovered that the .live() stops working.
I get the error TypeError: $(...).live is not a funct

相关标签:
10条回答
  • 2020-11-22 04:02

    I tend not to use the .on() syntax, if not necessary. For example you can migrate easier like this:

    old:

    $('.myButton').live('click', function);
    

    new:

    $('.myButton').click(function)
    

    Here is a list of valid event handlers: https://api.jquery.com/category/forms/

    0 讨论(0)
  • 2020-11-22 04:04

    You can avoid refactoring your code by including the following JavaScript code

    jQuery.fn.extend({
        live: function (event, callback) {
           if (this.selector) {
                jQuery(document).on(event, this.selector, callback);
            }
            return this;
        }
    });
    
    0 讨论(0)
  • 2020-11-22 04:05

    A very simple fix that doesn't need to change your code, just add jquery migration script, download here https://github.com/jquery/jquery-migrate/

    It supplies jquery deprecated but needed functions like "live", "browser" etc

    0 讨论(0)
  • 2020-11-22 04:06

    Forward port of .live() for jQuery >= 1.9 Avoids refactoring JS dependencies on .live() Uses optimized DOM selector context

    /** 
     * Forward port jQuery.live()
     * Wrapper for newer jQuery.on()
     * Uses optimized selector context 
     * Only add if live() not already existing.
    */
    if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
      jQuery.fn.extend({
          live: function (event, callback) {
             if (this.selector) {
                  jQuery(document).on(event, this.selector, callback);
              }
          }
      });
    }
    
    0 讨论(0)
  • 2020-11-22 04:07

    The jQuery API documentation lists live() as deprecated as of version 1.7 and removed as of version 1.9: link.

    version deprecated: 1.7, removed: 1.9

    Furthermore it states:

    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()

    0 讨论(0)
  • 2020-11-22 04:11

    If you happen to be using the Ruby on Rails' jQuery gem jquery-rails and for some reason you can't refactor your legacy code, the last version that still supports is 2.1.3 and you can lock it by using the following syntax on your Gemfile:

    gem 'jquery-rails', '~> 2.1', '= 2.1.3'
    

    then you can use the following command to update:

    bundle update jquery-rails
    

    I hope that help others facing a similar issue.

    0 讨论(0)
提交回复
热议问题