2011-11-25 79 views
1

我存储了一个jquery对象(html元素的集合),但是当我在另一个函数中引用该对象时,它返回为'undefined'!这里是我的代码:为什么我不能在回调中引用我的jQuery对象?

this.container = $('#slide-menu'), // The menu container (e.g. a UL) 
this.items = this.container.find('.menu-item'); // The menu items (e.g. all li's) 
this.links = this.items.find('.link'); // The menu links 

this.getCurrent(); // Set the current menu-item 
this.getPrev(); // Set the previous menu-item 
this.getNext(); // Set the next menu-item 

console.log(this.items); // !!! The items exist here !!! 

// Setup the menu items click events: 
this.items.bind('click', function(e) { 

    console.log(this.items); // !!! But not here !!! ??? 

    e.preventDefault(); 
    o = $(e.currentTarget); // Set jquery object 

    if (!o.hasClass('active')) { // Prevent action on current menu-item 
     this.items.find('.active').removeClass('active'); // Remove the current active menu-item 
     o.addClass('active'); // Set new active menu item 

任何人都不会有为什么发生这种情况,因为它的驾驶我疯了,只要我能看到这不应该是可能的任何想法。 JavaScript是坏了?!嗯,你觉得怎么样?

回答

4

什么时候jQuery对象不是对象?

从来没有。

当它是未定义的!

或当它不是你认为它的地方。

任何人都不会有为什么发生这种情况,因为它的驾驶 我疯了,只要我能看到这不应该是可能的任何想法。是 javascript坏了?嗯,你觉得怎么样?

不,Javascript没有“破”。

你假设this.items总是指同一件事。它不是。在bind里面,this是被点击的东西,而不是回调函数之外的东西。

在你的回调中,你应该写$('#slide-menu').find('menu-item')而不是this.items

+0

Doh!是的,你是绝对正确的,菜鸟错误对不起。非常感谢!! – Chris

+0

哈哈 - 是javascript坏了? > jk。再次感谢,现在工作! – Chris

2

这是一个范围问题。

this您的点击事件处理程序外部与处理程序内部的this不相同。处理程序内部指的是被点击的元素。在它之外它可能是全球窗口对象。

这应该很好地工作:

var items = this.container.find('.menu-item'); 

items.bind('click', function(e) { 
    console.log(items); 

不要在JavaScript中使用this,除非你真正需要。

+0

我不喜欢那个循环依赖的外观。 –

+0

@ TomalakGeret'kal循环依赖? –

+0

DOM中引用的函数绑定到Javascript中的变量。而你的Javascript有一个参考功能。我认为?我不会从函数内部引用'items',而是在回调中重新获取它。 –

相关问题