通常当你调用root.find('.test'),它会返回所有元素test类里面 root.有没有办法考虑root作为可能的候选人呢?
换句话说,用html
<div id="x" class="test"></div>
Run Code Online (Sandbox Code Playgroud)
,$('#x').find('.test')将返回1个元素而不是零.
如果我们概括它,在表达式中root.find('condition1 condition2 condition3')我也希望condition1对其进行测试root.
我正在考虑创建一个自定义帮助方法,但也许有更优雅的东西.
谢谢!
没有干净的方法来做到这一点,你可以得到的最接近的是这样使用.andSelf():
$('#x').find('.test').andSelf().filter('.test')
Run Code Online (Sandbox Code Playgroud)
如果.andSelf()采用选择器,它会稍微更清晰(并且效率更高,没有双重过滤),但只会更短一些.
内置方法的最快(但有点混乱)方法涉及复制ID选择器,如下所示:
$('#x').find('.test').add($('#x').filter('.test'));
//or, shorter but slower:
$('#x').find('.test').add($('#x.test'));
Run Code Online (Sandbox Code Playgroud)