如何正确存储复杂的jquery选择器链以便重用?

Tra*_*s J 4 javascript jquery selector

TL;博士? jsFiddle Demo

我有一个场景,我需要重新发出一个jquery选择器,因为dom更改.选择器非常重要.

$("#protocol :first-child").nextUntil('.sampleDetails','.detailHolder')
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,我尝试将其分解为部分并存储以供重复使用:

var selector = [];
selector.push("#protocol :first-child");
selector.push("nextUntil"); 
selector.push(['.sampleDetails','.detailHolder']);
Run Code Online (Sandbox Code Playgroud)

这种方式当我需要构建我可以使用的选择器时

$(selector[0])[selector[1]](selector[2]);
Run Code Online (Sandbox Code Playgroud)

但是,参数nextUntil需要两个参数.使用数组不起作用,使用"'.sampleDetails','.detailHolder'"也不起作用.我试图用callapply,但得到了一个错误说"Uncaught TypeError: Object [object Array] has no method 'pushStack' ".

存储此类选择器链的正确方法是什么?

lon*_*day 10

当然,简单的方法是使用函数,而不是复杂的选择器数组?

var getElements = function() {
    return $("#protocol :first-child").nextUntil('.sampleDetails','.detailHolder');
};
Run Code Online (Sandbox Code Playgroud)

然后您可以根据需要多次调用它:

var elements = getElements();
Run Code Online (Sandbox Code Playgroud)

甚至:

getElements().show();
Run Code Online (Sandbox Code Playgroud)

  • 尼斯.哈哈,不知道为什么我没想到这一点.作品:[demo](http://jsfiddle.net/SsLC3/). (3认同)