我试图弄清楚如何在 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 中使用变量选择后代?
最佳答案
你的引言太多了
$(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>
关于javascript - 可以在 Jquery 中使用变量作为后代选择器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132085/