Javascript jQuery 插件返回“无法读取未定义的属性”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4161815/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:10:02  来源:igfitidea点击:

jQuery plugin returning "Cannot read property of undefined"

javascriptjquerypluginsundefined

提问by Oscar Godson

I'm trying to do something i've done numerous times. I can't figure out why this isn't working. No matter how i write the jQuery code, it doesn't work. menuitems[i].action()just does NOT work. Below is Example 1in which this example, no matter what item is clicked it returns the last item's action (in this example it's the alert('Forward!')). The 2nd returns undefined property. The full error below.

我正在尝试做一些我做过很多次的事情。我不明白为什么这不起作用。无论我如何编写 jQuery 代码,它都不起作用。menuitems[i].action()只是不起作用。下面是示例 1,在该示例中,无论单击什么项目,它都会返回最后一个项目的操作(在本示例中为alert('Forward!'))。第二个返回未定义的属性。下面的完整错误。

My jQuery plugin is called like this (examples below are what happen with this same call):

我的 jQuery 插件是这样调用的(下面的例子是同一个调用发生的情况):

$('p').contextMenu([
    {
        name:'Back',
        action:function(){
            alert('Back!');
        },
        icon:'http://cdn.iconfinder.net/data/icons/crystalproject/16x16/actions/agt_back.png'
    },
    {
        name:'Forward',
        action:function(){
            alert('Forward!');
        },
        icon:'http://cdn.iconfinder.net/data/icons/crystalproject/16x16/actions/agt_forward.png'
    }
]);

Example 1:

示例 1:

for (i in menuitems){
    $('<li/>',{
        'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
        'class':o.itemClass,
        'click':function(){
            menuitems[i].action();
        }
    }).appendTo('.'+o.listClass);
}

This returns an alert with Forward! no matter which item, Back or Forward, is clicked.

这将返回一个带有 Forward! 的警报!无论单击后退或前进哪个项目。

Example 2:

示例 2:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    $('<li/>',{
        'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
        'click':function(){
            menuitems[i].action();
        },
        'class':o.itemClass
    }).appendTo('.'+o.listClass);
}

I get:

我得到:

Uncaught TypeError: Cannot read property 'action' of undefined

未捕获的类型错误:无法读取未定义的属性“动作”

Other random things i tried were detaching the click and reattaching it outside of that appendTo()block, changed action()to newtest()to make sure it wasn't conflicting with any built in keywords. I also tried doing a $('body').append('<li>{blah blah}</li>').find('li').click(function(){/*blah blah*/});but it still returned the same thing. I'm outta ideas!

我尝试的其他随机操作是分离点击并将其重新附加到该appendTo()块之外,更改action()newtest()以确保它与任何内置关键字不冲突。我也尝试过,$('body').append('<li>{blah blah}</li>').find('li').click(function(){/*blah blah*/});但它仍然返回同样的事情。我没主意了!

回答by nxt

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

问题是“i”是递增的,所以当点击事件被执行时,i 的值等于 len。一种可能的解决方案是在函数中捕获 i 的值:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

在上面的示例中,匿名函数创建了一个新的作用域,它捕获 i 的当前值,以便在触发 click 事件时使用局部变量而不是 for 循环中的 i。

回答by Siedrix

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

通常这个问题是在最后一次迭代中你有一个空对象或未定义对象。在你的 cicle 中使用 console.log() 来检查这是否发生了。

Sometimes a prototype in some place add an extra element.

有时某个地方的原型会添加额外的元素。

回答by byJeevan

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4*from *jquery-1.10.2*.And error cleared.

我对“视差”插件有同样的问题。我将 jQuery librery 版本更改为*jquery-1.6.4*from*jquery-1.10.2*.并且错误已清除。