2

我是一个 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#container 填充了 ul 元素,每个元素都超过一个 li。我想访问第 n 个 li 并淡入该元素,但控制台向我抛出了一个错误,指出fadeIn 没有这样的方法。你能帮我整理一下吗?

4

3 回答 3

5

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

当你这样做时:this.moreItems[this.current]你实际上是从 jquery 数组中提取 DOMElement --> 你必须把它变成一个 jquery 对象才能调用 fadeIn() !

$(this.moreItems[this.current]).fadeIn();

您还可以使用.eq(index)将匹配集过滤为与索引对应的唯一元素:

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

演示


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

  1. 要将函数添加到原型中,您应该执行以下操作:

    MyApp.prototype.myUsefulFunction = function() {}
    

    并不是MyApp.prototype.myUsefulFunction() {}

  2. 使用new运算符返回一个新的实例MyApp

    var app = new MyApp(config); // also spelling mistake: myApp != MyApp !!
    
于 2012-03-10T15:02:25.337 回答
1

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

$.fn.myUsefulFunction=function() {
    return this.each(function(){
        $(this).fadeIn();

    })
}

您现在可以像使用任何其他 jQuery 方法一样使用它

   $(selector).myUsefulFunction()
于 2012-03-10T15:10:40.227 回答
0

题外话:

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

    var app = new myApp(config);

  2. myAppMyApp是不同的变量。

于 2012-03-10T15:08:28.633 回答