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

mgi*_*nbr 5 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
Run Code Online (Sandbox Code Playgroud)

我想修改$(unrelated)对象以包含this堆栈,所以第二个例子可以工作.这是jsFiddle中的完整示例.

Bru*_*lva 2

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

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