为什么我不能在回调中引用jQuery对象

Why can I not reference my jQuery object inside a callback?

本文关键字:引用 jQuery 对象 回调 不能 为什么      更新时间:2023-09-26

我存储了一个jquery对象(html元素的集合),但是当我在另一个函数中引用该对象时,它会返回为"未定义"!下面是我的代码:

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坏了吗?嗯,你觉得怎么样?

什么时候一个jquery对象不是对象?

当它是未定义的!

或者当它不在你想的地方。

有人知道为什么会这样吗?因为它在开车我疯了,在我看来这是不可能的。是Javascript坏了?!嗯,你觉得怎么样?

不,Javascript没有"坏"。

您假设this.items总是指相同的东西。但事实并非如此。在你的bind中,this是被点击的东西,而不是它在回调函数之外的任何东西。

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

这是一个范围问题。

点击事件处理程序外的this与处理程序内的this不同。在处理程序中,它指的是被单击的元素。外部可能是全局窗口对象。

这应该可以正常工作:

var items = this.container.find('.menu-item');
items.bind('click', function(e) {
     console.log(items); 

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