Geu*_*uis 6 javascript jquery jquery-selectors
我遇到的情况是我从一个html字符串创建一个jQuery对象,需要用特定的类选择其中的所有元素.
我发现奇怪的是它返回一个或另一个,这取决于我使用的选择机制类型.此处显示了一个测试用例:
var tmpl = '<ul><li class="foo">TEST</li></ul><div class="foo">BAR</div>';
console.log( $('.foo', tmpl) ); //[<li class="foo">TEST</li>]
console.log( $(tmpl).find('.foo') ); //[<li class="foo">TEST</li>]
console.log( $(tmpl).filter('.foo') ); //[<div class="foo">BAR</div>]
Run Code Online (Sandbox Code Playgroud)
在此示例中,ul中的li元素和非后代div都具有类"foo".在示例中,我使用.foo选择器并将上下文设置为模板字符串.其次,我在字符串上使用.find().最后,我在字符串上使用.filter().
有人可以解释选择器机制为何如此行事,以及如何实现我在开始时提到的目标?
| 归档时间: |
|
| 查看次数: |
959 次 |
| 最近记录: |