您可以在 Jquery 中使用变量作为后代选择器吗?

Can you use variables as descendant selectors in Jquery?

我正在尝试弄清楚如何使用变量在 Jquery 中创建 selectors,就像后代 selectors 一样。

我知道您可以使用 .add() 添加变量,但我还没有弄清楚如何使用它们来缩小 selection。

这是我一直在玩的东西:

//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>

我如何 select 后代使用 Jquery 中的变量?

改变这个

 $("#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"});

你引用的太多了

$(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>