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

标签 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>

如何在 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/

相关文章:

javascript - 隐藏和显示 HTML 表格中的内容

jquery - 通过 JQuery JSONP 调用 Google Ajax 搜索 API

javascript - 以 Angular 观察对象数组并信任 html

javascript - Ex.Message.alert 的 Sencha 触摸叠加效果未关闭

javascript - 在 IE 中使用 JS、HTML 和 CSS 自定义文件上传

javascript - 数组元素和属性?

javascript - 与在 jquery 中获取类名相关的问题

html - 垂直对齐表单组 Bootstrap

javascript - 如果 URL 更改,则重定向页面返回

javascript - 使用 Promises 使用 sinon stub 对函数进行测试