我可以在Jquery中结合使用变量和选择器吗? [英] Can I combine a variable and a selector in 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.
推荐答案
使用
$('.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...
这篇关于我可以在Jquery中结合使用变量和选择器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文