如何将 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 的堆栈,这样第二个示例就可以工作。这是完整的example在 jsFiddle 中。
请您参考如下方法:
$.fn.myPlugin = function(related) {
if ( related == "getRelated" )
return this.pushStack($(this.data("related")).get()); // Want to preserve stack
return this.data("related",related);
};
您需要将元素插入堆栈,以便 end() 返回到它。
