在我的插件中使用jQuery的end()

时间:2012-02-06 00:55:11

标签: jquery jquery-traversing

如何将jQuery对象的堆栈复制到另一个jQuery对象,所以即使返回完全不相关的对象,我也可以在插件中使用end?例如:

$(myselector)
    .next()             // Destructive operation
        .doSomething()
    .end()              // Goes back to "myselector"
    .doSomethingElse(); // Works fine!

$.fn.myPlugin = function() {
    return $(unrelated); // No stack, can't call "end" on it
};

$(myselector)
    .myPlugin()         // Destructive operation
        .doSomething()
    .end()              // Goes back to nowhere, since the stack is empty
    .doSomethingElse(); // Doesn't work

我想修改$(unrelated)对象以包含this的堆栈,因此第二个示例可行。这是jsFiddle中的完整example

3 个答案:

答案 0 :(得分:2)

$.fn.myPlugin = function(related) {
    if ( related == "getRelated" )
        return this.pushStack($(this.data("related")).get()); // Want to preserve stack
    return this.data("related",related);
};

您需要将元素推送到堆栈,以便end()返回到它。

答案 1 :(得分:0)

对我来说,看起来你编写插件的方式会干扰jQuery的逻辑,因为你返回的是jQuery可能没想到的东西。这只是猜测,因为我根本不了解jQuery。

也许你可以在.doSomething()中做你想做的事情吗?

答案 2 :(得分:0)

如果你查看$('#a')上的数据,它只是一个字符串,说'#c'不是一个真正的jQuery对象。我为您更新了代码http://jsfiddle.net/89gkD/3/