Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

前端 未结 6 1185
生来不讨喜
生来不讨喜 2020-12-29 01:57

I\'m teaching myself AJAX to AJAXify my site. In my template, I have the following JS code to get some JSON data from a view then append the data to a div.

f         


        
相关标签:
6条回答
  • 2020-12-29 02:13

    Make sure you're passing a selector to jQuery, not some form of data:

    $( '.my-selector' )
    

    not:

    $( [ 'my-data' ] )
    
    0 讨论(0)
  • 2020-12-29 02:13

    In case you are appending to the DOM, make sure the content is compatible:

    modal.find ('div.modal-body').append (content) // check content
    
    0 讨论(0)
  • 2020-12-29 02:14

    If you use ES6 anon functions, it will conflict with $(this)

    This works:

    $('.dna-list').on('click', '.card', function(e) {
      console.log($(this));
    });
    

    This doesn't work:

    $('.dna-list').on('click', '.card', (e) => {
      console.log($(this));
    });
    
    0 讨论(0)
  • 2020-12-29 02:27

    In my case, this error happened because my HTML had a trailing linebreak.

    var myHtml = '<p>\
        This should work.\
        But does not.\
    </p>\
    ';
    
    jQuery('.something').append(myHtml); // this causes the error
    

    To avoid the error, you just need to trim the HTML.

    jQuery('.something').append(jQuery.trim(myHtml)); // this works
    
    0 讨论(0)
  • 2020-12-29 02:35

    I had a similar issue. I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.

    0 讨论(0)
  • The same issue came up for me inside of $elms.each().

    Because:

    1. the function you pass to .each(Function) exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, and
    2. because other similar looping methods give current the element in the array before the index

    you may be tempted to do this:

    $elms.each((item) => $(item).addClass('wrong'));
    

    When this is what you need:

    $elms.each((index, item) => $(item).addClass('wrong'));
    
    0 讨论(0)
提交回复
热议问题