5

如何将 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 中的完整示例

4

3 回答 3

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() 回到它。

于 2012-02-06T01:02:04.127 回答
0

对我来说,您编写插件的方式似乎扰乱了 jQuery 的逻辑,因为您返回的东西可能不是 jQuery 所期望的。这只是一个猜测,因为我根本不了解 jQuery。

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

于 2012-02-06T01:05:55.500 回答
0

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

于 2012-02-06T01:07:13.273 回答