jQuery “Object function (e,t){return new v.fn.init

2019-08-01 20:55发布

问题:

I'm following @coreyward's example for putting object edit forms in modal dialog windows in Rails, which is outlined in this answer and updated for rails 3.1 in this gist.

I'm using Rails 3.2.8 and jQuery-Rails 2.1.3 (jQuery 1.8.2 is what's loading in the app). However, this coffeescript from the gist raises the error in the title, on line 7 (right after the comment).

$ ->
  $modal = $('#modal')
  $modal_close = $modal.find('.close')
  $modal_container = $('#modal-container')

  # Handle modal links with the data-remote attribute
  $.on 'ajax:success', 'a[data-remote]', (xhr, data, status) ->
    $modal
      .html(data)
      .prepend($modal_close)
      .css('top', $(window).scrollTop() + 40)
      .show()
    $modal_container.show();

  $.on 'click', '#modal .close', ->
    $modal_container.hide()
    $modal.hide()
    false

Comments on this question made me this a jQuery version issue might be the cause, which is why I checked my jQuery version, but obviously this jQuery isn't as old as the one which solved that problem. I've also verified that jQuery is loaded before this script (or at least, it's above this script in the load order).

I put the coffeescript above into a fiddle which demonstrates the problem (see your console for the error). (That also makes me think this isn't a problem with my setup.) I'll try different versions of jQuery to see if they resolve it, but maybe the code is just wonky? I don't know coffeescript well enough to see errors which might be obvious to others.

回答1:

Replacing $.on by $(document).on removes the errors ... The on method needs to be called on a DOM element from what I can tell, never saw it called on the jQuery root object before...