jQuery 和链接问题

标签 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
}

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

<小时/>

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

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

    MyApp.prototype.myUsefulFunction = function() {}
    

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

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

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

关于jQuery 和链接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9647378/

相关文章:

javascript - 使用 AJAX 在 PHP 文件中调用函数,并使用特定于数据库中记录的 ID 来更新记录

jQuery 如何绑定(bind)数据?

java - 在 Struts 2 中使用 jQuery 的 Ajax 表单提交按钮

JQuery:可以给.load添加过渡效果吗

python - itertools 的 chain.from_iterable 和 chain() 的更简化解释

python - 如何停止链中间失败任务的链执行?

openssl - 我可以在没有私钥的情况下将多个证书合并为一个吗?

Javascript - 无法理解闭包

javascript - jQuery 自动完成(devbridge)lookupFilter 搜索多个属性

javascript - 钛合金范围链