我可以在Jquery中结合使用变量和选择器吗?

我可以在Jquery中结合使用变量和选择器吗?

问题描述:

说我有这个HTML:

<div class="top">top
    <div class="middle">middle
        <div class="bottom">bottom</div>
    middle</div>
top</div>
<div class="middle">outside middle</div>

是否可以为选择器创建变量,然后将其用作另一个选择器?这是我要尝试的操作,但这不起作用:

Is there a way to create a variable for a selector and then use it as part of another selector? This is what I'm trying to do, but this does't work :

$top = $('.top');

$($top + ' .middle').click(function(){
    $(this).toggleClass('green');
});

我确定我不需要重新选择.top,因为这就是变量的作用,所以我确定我需要对$ top进行操作,我不确定是什么.

I'm sure I don't need to re-select .top as that's what the variable did, so I'm sure I need to do something with $top, I'm just not sure what.

http://jsfiddle.net/ftXLx/1/

使用

$('.middle', $top)

$top.find('.middle')

您还可以简单地将选择器(即字符串)与

You could also have simply combined the selectors, which are strings, with

$($top.selector + ' .middle')

但这只会更慢且可读性更差...

but this would only be slower and less readable...