我正试图找出如何使用变量在Jquery中像后代选择器一样制作选择器。
我知道您可以使用.add()添加变量,但我无法弄清楚如何使用它们缩小选择范围。
下面是我一直在玩的东西:
//descendant selector using classnames:
$("div.aReallyLongClassName li.anotherReallyLongClassName").css({background:"red"});
//Using the jquery below doesn't work, but the console displays the classnames exactly how they appear in the jquery above.
var foo = 'div.aReallyLongClassName';
var bar = 'li.anotherReallyLongClassName';
$("#console").html('"' + foo + ' ' + bar + '"');
$('"' + foo + ' ' + bar + '"').css({background:"green"});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aReallyLongClassName">
<ul>
<li>No background</li>
<li class="anotherReallyLongClassName">Red BG = Fail, Green BG = Success!</li>
</ul>
</div>
<div class="foobar">
<ul>
<li>No background</li>
<li class="anotherReallyLongClassName">No background</li>
</ul>
</div>
Computed selector is:
<span id="console"></span>
如何使用Jquery中的变量选择后代?
发布于 2015-05-08 20:11:24
你引用的太多了
$(foo + ' ' + bar).css({background:"green"});就行了。你的片段更新了绿色:
//descendant selector using classnames:
$("div.aReallyLongClassName li.anotherReallyLongClassName").css({background:"red"});
//Using the jquery below doesn't work, but the console displays the classnames exactly how they appear in the jquery above.
var foo = 'div.aReallyLongClassName';
var bar = 'li.anotherReallyLongClassName';
$("#console").html('"' + foo + ' ' + bar + '"');
$(foo + ' ' + bar).css({background:"green"});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aReallyLongClassName">
<ul>
<li>No background</li>
<li class="anotherReallyLongClassName">Red BG = Fail, Green BG = Success!</li>
</ul>
</div>
<div class="foobar">
<ul>
<li>No background</li>
<li class="anotherReallyLongClassName">No background</li>
</ul>
</div>
Computed selector is:
<span id="console"></span>
发布于 2015-05-08 20:11:17
改变这个
$("#console").html('"' + foo + ' ' + bar + '"');对此:
$("#console").append(foo.html());
$("#console").append(bar.html());或者这样说:
$("#console").html(foo.html() + bar.html());否则,您将将字符串(如div.aReallyLongClassName)附加到$("#console")。
或者,您可以创建jquery对象并像这样使用它们:
var foo = $('div.aReallyLongClassName');
var bar = $('li.anotherReallyLongClassName');
$("#console").append(foo);
$("#console").append(bar);
foo.css({background:"green"});
bar.css({background:"green"});https://stackoverflow.com/questions/30132085
复制相似问题