我想写一个优雅的解决方案,通过在不同的上下文列表中搜索来选择相同的标签
//i have this not editable code
var c1$ = $('#context1'),
c2$ = $('#context2'),
c3$ = $('#context3');
//I want to improve the code and 'only from here on
var selector = 'a.select';
c1$.find(selector).css('color','red');
c3$.find(selector).css('color','red');我正在为任意数量的上下文寻找解决方案
发布于 2012-05-02 05:35:13
您可以使用$.add()构建上下文,然后将其用作选择器的context参数中的单个jQuery对象:
var $foo = $("#foo"),
$bar = $("#bar");
var $context = $foo.add($bar);
$("a.select", $context).css("color", "red");发布于 2012-05-02 07:15:57
为什么不加载一个上下文列表,然后执行foreach来查找每个上下文中的“a.select”?
发布于 2012-05-03 07:43:13
我的绝望而不优雅的解决方案
var contexts = [$('#context1'),$('#context2'),$('#context3')];
//list of contexts in single variable(arbitrary number!)
var selector = 'a.select';
//same selector for all variable contexts
var cons$ = $([]);
//empty temporary selector
for(i in contexts)
cons$ = cons$.add(contexts[i]);
var allmatches$ = cons$.find(selector);
//here processing allmatches$
allmatches$.css("color", "red");
//now apply css in one stephttps://stackoverflow.com/questions/10404539
复制相似问题