我想写一个优雅的解决方案,通过搜索选择相同的标签 不同背景的列表
//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');
我正在寻找任意数量的上下文的解决方案
答案 0 :(得分:8)
您可以使用$.add()
构建上下文,然后在选择器的context参数中将其用作单个jQuery对象:
var $foo = $("#foo"),
$bar = $("#bar");
var $context = $foo.add($bar);
$("a.select", $context).css("color", "red");
答案 1 :(得分:0)
为什么不加载上下文列表,然后在每个上下文中找到'a.select'?#。
答案 2 :(得分:0)
我绝望的不优雅的解决方案
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 step