javascript 为什么我会收到这个 JS 错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5590776/
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
Why am I getting this JS error?
提问by Justin Meltzer
I get this JS error:
我收到这个 JS 错误:
jquery-1.5.1.min.js:16Uncaught TypeError: Cannot set property '_renderItem' of undefined
d.d.extend._Deferred.f.resolveWithjquery-1.5.1.min.js:16
d.d.extend.readyjquery-1.5.1.min.js:16
d.c.addEventListener.A
and it's from this code for the jquery UI autocomplete plugin in my application.js file:
它来自我的 application.js 文件中 jquery UI 自动完成插件的代码:
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.topic.name + "</a>" )
.appendTo( ul );
};
I get this code whenever I load a page that does NOT have the text field that the autocomplete code is acting on. Why and how can I get rid of this error?
每当我加载没有自动完成代码所作用的文本字段的页面时,我都会收到此代码。为什么以及如何摆脱此错误?
I'd like to note that although I am getting this error, my application is working normally. Should I even be worrying about this error?
我想指出,虽然我收到此错误,但我的应用程序运行正常。我应该担心这个错误吗?
回答by Mark Kahn
$(...).data('autocomplete')
is undefined, and you can't set a property of undefined. try:
未定义,并且您不能设置未定义的属性。尝试:
var obj = $(...).data('autocomplete');
obj && (obj._renderItem = function(){
...
});
回答by al000y
this problem appeared to me when i upgrade the jquery ui from old one to 1.10.0
当我将 jquery ui 从旧版升级到 1.10.0 时,我出现了这个问题
just change
只是改变
$('.foo').data("autocomplete")._render...;
To
到
$('.foo').data("uiAutocomplete")._render...;
回答by nathan gonzalez
why not just wrap the autocomplete code in a check to see if that element exists?
为什么不将自动完成代码包装在检查中以查看该元素是否存在?
something like this:
像这样:
if ($'#myElementId').length) {
$('#myElementId').data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.topic.name + "</a>" )
.appendTo( ul );
};
}
回答by Blender
I think .data("autocomplete")
isn't returning an object, as the error says:
我认为.data("autocomplete")
没有返回一个对象,因为错误说:
Cannot set property '_renderItem' of undefined
无法设置未定义的属性“_renderItem”
If you are doing this:
如果你这样做:
$('.foo').data("autocomplete")._render...;
You try breaking it up:
你试着打破它:
$('.foo').data("autocomplete");
$('.foo')._renderItem = ...;
I've never encountered _renderItem
, so I'll look more in to that.
我从来没有遇到过_renderItem
,所以我会多看看。
Actually, this question seems to explain a problem really similar to your's: Using _renderItem kind of breaks autocomplete field
实际上,这个问题似乎解释了一个与您的问题非常相似的问题:Using _renderItem kind ofbreaks autocomplete field