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

时间:2015-05-08 20:09:07

标签: javascript jquery html jquery-selectors

我试图弄清楚如何使用变量在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>
&#13;
&#13;
&#13;

如何在Jquery中使用变量选择后代?

2 个答案:

答案 0 :(得分:2)

你的报价太多了

$(foo + ' ' + bar).css({background:"green"});

会做的。您的代码段已更新且为绿色:

&#13;
&#13;
//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"});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

更改此

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