2008-12-09 78 views
1

主要的jQuery方法需要第二個可選參數來爲搜索提供上下文。 如有沒有辦法在jQuery中執行'scoped'add()?

$(".setA", ancestorOfSetsA); 

然而,jQuery的add()方法不接受這種情況下的說法。我試圖做到的是:

$(".setA", ancestorOfSetsA).add(".setB", ancestorOfSetsB); 

我通過一個插件,將超載add()方法嘗試這一點,但我無法弄清楚如何將兩個jQuery的對象合併成一個jQuery對象。

我想找到一種方法來與jQuery做一個作用域add(),但如果我能找到一種方法來合併到jQuery對象,我會自己寫一個。

回答

2

你可以傳遞一個jQuery集合到add一樣好選擇字符串:

$(".setA", ancestorOfSetsA).add($(".setB", ancestorOfSetsB)); 

如果你想重載add,那麼你就必須要小心,以支持它的所有行爲。有人(你可能會使用一個插件)可以做到這一點:

$(selector).add('<div>new element</div>').appendTo(somethere); 

更新時間:

這裏是jQuery的當前add函數修改爲使用上下文參數:

jQuery.fn.add = function(selector, context) { 
    return this.pushStack(jQuery.unique(jQuery.merge(
     this.get(), 
     typeof selector == 'string' ? 
      jQuery(selector, context) : 
      jQuery.makeArray(selector) 
    ))); 
} 
+0

基礎的在您的意見,這是我想出了: $ .fn._add = $ .fn.add; $ .fn.add = function(selector,context){ return this._add(context? $(selector,context): selector ); }; 思考? – jasonkarns 2008-12-09 21:16:09

相關問題