【问题标题】:How can I make my jQuery plugin respect end()?如何让我的 jQuery 插件尊重 end()?
【发布时间】:2011-06-23 18:22:39
【问题描述】:

对于大多数更改选择的 jQuery 函数调用,可以使用 end 在选择中返回一个步骤。例如:

$('#myElement').parent().show().end().css('color', '#ff0000');

这会显示父元素,然后将原始选择变为红色。

但是,当我定义自己的过滤选择的 jQuery 插件时,我没有获得此功能。例如:

$.fn.nextBarOne = function(selector) {
    var ret = this.next().next();

    return (typeof selector === 'undefined') ? ret : ret.filter(selector);
}

如果我现在做$('#myElement').nextBarOne().show().end(),我不会回到原来的选择。显然这是因为函数内部调用了两次next,然后有时又调用了filter

如何定义一个 jQuery 插件,让我可以像内置函数一样使用end

【问题讨论】:

  • 在 jQuery 源代码中查找“pushStack”;基本上你的代码会像 jQuery 的“find”、“parents”等函数一样调用它。

标签: javascript jquery jquery-plugins jquery-selectors


【解决方案1】:

使用.next()遍历后设置prevObject指向原来的jQuery对象。

$.fn.nextBarOne = function(selector) {
    var self = this,
        ret = (typeof selector === 'undefined') ? 
                this.next().next() : this.next().next().filter(selector);
    ret.prevObject = self; 
    return ret;
}

编辑:

pushStack() 可能更干净。我还在pushStack 调用中包含了选择器。

$.fn.nextBarOne = function(selector) {
    var ret = (typeof selector === 'undefined') ? 
                this.next().next() : this.next().next().filter(selector);
    return this.pushStack(ret, "nextBarOne", selector || "");           
}

An example here

【讨论】:

  • 看起来有一个共同的模式 - 但是现在我想起来我在看 1.4.4,而不是 1.5;我怀疑事情已经改变了
  • @Russ 除非你使用选择器——filter 也明确设置了prevObject,否则它会起作用。我认为您需要在所有其他操作之后放置 ret.prevObject 行...
  • @Russ 非常感谢,效果很好。我无法相信the API for this is 多么没用。 Updated jsFiddle.
猜你喜欢
  • 1970-01-01
  • 2012-02-27
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多