jQuery和链接问题

jQuery和链接问题,jquery,chain,Jquery,Chain,我是jQuery新手,也许我要问一个非常基本的问题,但我真的很难弄清楚为什么jQuery链接在我的情况下不起作用 var container = $('#container'), items = container.find('ul.items'), moreItems = items.children('li.moreItems'); var config = { container : container, items : items, moreItems : moreItems } v

我是jQuery新手,也许我要问一个非常基本的问题,但我真的很难弄清楚为什么jQuery链接在我的情况下不起作用

var container = $('#container'),
items = container.find('ul.items'),
moreItems = items.children('li.moreItems');

var config = {
container : container,
items : items,
moreItems : moreItems
}

var app = myApp(config);

function MyApp(config) {
this.container = config.container;
this.items = config.items;
this.moreItems = config.moreItems;
this.current = 0;
}

MyApp.prototype.myUsefulFunction() {
this.moreItems[this.current].fadeIn();
}

假设我有一个div容器,里面装满了ul元素,每个元素都有一个以上的li。我想访问第n个li并淡入元素,但控制台返回了一个错误,说明fadeIn没有这样的方法。您能帮我整理一下吗?

jQuery返回一个jQuery对象,它是一种包含doElement的数组

执行此操作时:
this.moreItems[this.current]
实际上是从jquery数组中提取domeElement-->必须将其转换为jquery对象才能调用fadeIn()

还可以使用将匹配集筛选为与索引对应的唯一元素:

this.moreItems.eq(this.current).fadeIn();


除此之外,您在问题中显示的代码有几个语法错误:

  • 要向原型中添加函数,应执行以下操作:

    MyApp.prototype.myUsefulFunction = function() {}
    
    而不是
    MyApp.prototype.myUsefulFunction(){}

  • 使用
    new
    操作符返回
    MyApp的新实例

    var app = new MyApp(config); // also spelling mistake: myApp != MyApp !!
    
  • 离题:

  • 要创建类的实例,您需要使用new

    var-app=新的myApp(配置)

  • myAppmyApp是不同的变量


  • 要创建用于链接的jQuery方法,需要扩展jQuery.fn

    $.fn.myUsefulFunction=function() {
        return this.each(function(){
            $(this).fadeIn();
    
        })
    }
    
    您现在可以像使用任何其他jQuery方法一样使用它

       $(selector).myUsefulFunction()
    

    你是说这个吗?MyApp.prototype.myUsefulFunction=function(){this.moreItems[this.current].fadeIn();}
       $(selector).myUsefulFunction()