jQuery 未捕获的类型错误:无法读取未定义的属性“ownerDocument”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17594855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'ownerDocument' of undefined
提问by Denny
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.
我正在自学 AJAX 到 AJAXify 我的网站。在我的模板中,我使用以下 JS 代码从视图中获取一些 JSON 数据,然后将数据附加到 div。
function filter(type) {
$.getJSON(
'/activity_stream/global-activity-stream/',
{xhr: "true", filter: type},
function(data) {
$('.mainContent').children().remove();
$(data).appendTo('.mainContent');
});
}
$(".btn").click(function () {
filter("recent");
});
}
I think my view is returning proper JSON but now data is not being added to the .mainContent
div.
我认为我的观点正在返回正确的 JSON,但现在数据没有被添加到.mainContent
div 中。
It gives this error:
它给出了这个错误:
Uncaught TypeError: Cannot read property 'ownerDocument' of undefined.
未捕获的类型错误:无法读取未定义的属性“ownerDocument”。
回答by redolent
Make sure you're passing a selector to jQuery, not some form of data:
确保您将选择器传递给 jQuery,而不是某种形式的数据:
$( '.my-selector' )
not:
不是:
$( [ 'my-data' ] )
回答by Overload119
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.
我有一个类似的问题。我正在使用 jQuery.map 但我忘记在最后使用 jQuery.map(...).get() 来处理普通数组。
回答by Kevin Beal
The same issue came up for me inside of $elms.each()
.
在$elms.each()
.
Because:
因为:
- 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 - because other similar looping methods give current the element in the array before the index
- 您传递给的函数
.each(Function)
公开(至少)两个参数;第一个是索引,第二个是列表中当前元素中的元素,以及 - 因为其他类似的循环方法在索引之前给出了当前数组中的元素
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'));
回答by mehmet
In case you are appending to the DOM, make sure the content is compatible:
如果您要附加到 DOM,请确保内容兼容:
modal.find ('div.modal-body').append (content) // check content
回答by Eddie
If you use ES6 anon functions, it will conflict with $(this)
如果使用 ES6 anon 函数,会与 $(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));
});