我是一个 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 没有这样的方法。你能帮我解决一下吗?
最佳答案
jQuery 返回一个 jquery 对象,它是一种包含 DOMELements 的数组。
当你这样做时: this.moreItems[this.current]
你实际上从 jquery 数组中提取了 DOMElement --> 你必须将其转换为 jquery 对象才能调用 fadeIn( )!
$(this.moreItems[this.current]).fadeIn();
您还可以使用.eq(index)将匹配的集合过滤到与索引对应的唯一元素:
this.moreItems.eq(this.current).fadeIn();
<强> DEMO
<小时/>除此之外,您在问题中显示的代码片段有几个语法错误:
要将函数添加到原型(prototype),您应该执行以下操作:
MyApp.prototype.myUsefulFunction = function() {}
而不是
MyApp.prototype.myUsefulFunction() {}
使用
new
运算符返回MyApp
的新实例var app = new MyApp(config); // also spelling mistake: myApp != MyApp !!
关于jQuery 和链接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9647378/