简体   繁体   English

为什么以下jQuery选择器不返回这两个元素?

[英]Why is the following jQuery selector not returning both elements?

I've run into a situation where I am creating a jQuery object from an html string and need to select all elements within it with a particular class. 我遇到的情况是我从一个html字符串创建一个jQuery对象,需要用特定的类选择其中的所有元素。

What I'm finding odd is that its returning one or the other, depending on which type of selecting mechanism I'm using. 我发现奇怪的是它返回一个或另一个,这取决于我使用的选择机制类型。 A test case is shown here: 此处显示了一个测试用例:

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>]

http://jsfiddle.net/Rfq9F/ http://jsfiddle.net/Rfq9F/

In this example, both an li element in a ul and a non-descendant div have the class "foo". 在此示例中,ul中的li元素和非后代div都具有类“foo”。 In the example, I use the .foo selector and set context to the template string. 在示例中,我使用.foo选择器并将上下文设置为模板字符串。 Second, I use .find() on the string. 其次,我在字符串上使用.find()。 Finally, I use .filter() on the string. 最后,我在字符串上使用.filter()。

Can someone explain why the selector mechanisms are acting as they do, and also how to achieve the goal I mentioned in the beginning? 有人可以解释选择器机制为何如此行事,以及如何实现我在开始时提到的目标?

It's because it's not a single root node, but two ( ul and div ). 这是因为它不是单个根节点,而是两个( uldiv )。

Wrap everything in a <div> and it will work: 将所有内容包装在<div> ,它将起作用:

http://jsfiddle.net/Rfq9F/3/ http://jsfiddle.net/Rfq9F/3/

Calling $(tmpl) creates a set with two elements - the <ul> element and the <div class="foo"> element. 调用$(tmpl)会创建一个包含两个元素的集合 - <ul>元素和<div class="foo">元素。 .find() looks for elements that are descendents of any of the elements in the set that match the selector. .find()查找作为集合中与选择器匹配的任何元素的后代的元素。 .filter() returns any elements in the set that match the selector. .filter()返回集合中与选择器匹配的所有元素。

The first two lines: 前两行:

console.log( $('.foo', tmpl) );
console.log( $(tmpl).find('.foo') );

are equivalent, they're just two different ways to write the same thing. 等价,它们只是两种不同的方式来写同样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM