2012-05-03 112 views
5

我希望能够从一个HTML字符串构建一个jQuery对象并直接在里面搜索。从一个HTML字符串构建的jQuery对象中查找一个元素

例子:

htmlString = '<h3>Foo</h3><div class="groups"></div>' 
$html  = $(htmlString) 
$groups = $html.find('.groups') // Returns []. WTF? 

我预计find居然发现div元素。

如果你想知道更多关于我的问题的情况下,我开发一个应用骨干,并呈现一定的意见我有这样的事情:

render: -> 
    $html = $(@template(vehicle: @vehicle)) 
    $groups = $() 

    _(@groups).each (group)=> 
    subview = new App.Views.AttributesGroup(group: group, vehicle: @vehicle) 
    $groups = $groups.add(subview.render().el) 

    $(@el).html($html) 
    $(@el).find('.groups').replaceWith($groups) 
    @ 

我正在寻找一种更优雅的方式来达到相同的结果。

谢谢!


谢谢马特,这很清楚。我没有想到这个关于后代和兄弟姐妹的微妙之处,我感到很愚蠢。

所以我重构我的代码:

render: -> 
    $html = $(@template(vehicle: @vehicle)) 
    $groups = $html.filter('.groups') 

    _(@groups).each (group)=> 
    subview = new App.Views.AttributesGroup(group: group, vehicle: @vehicle) 
    $groups.append(subview.render().el) 

    $(@el).html($html) 
    @ 

现在只有一个DOM插入和代码看起来更清晰的给我。

回答

7

这是因为find()搜索jQuery对象中的元素的后代,但.groups元件 jQuery对象中的元件,从而将不被匹配。

相反,您需要使用filter()来搜索当前元素。

htmlString = '<h3>Foo</h3><div class="groups"></div>' 
$html  = $(htmlString) 
$groups = $html.filter('.groups'); 

不过,如果你有那么的<h3><span class="bar">Foo</span></h3><div class="groups"></div>htmlString,你不会发现.bar;这将是一个find()电话。

所以你需要检查两者;

htmlString = '<h3>Foo</h3><div class="groups"></div>' 
$html  = $(htmlString) 
$groups = $html.find('.groups').add($html.filter('.groups')); 
+0

谢谢马特,这很清楚。我没有想到这个关于后代和兄弟姐妹的微妙之处,我感到很愚蠢。以下是我重构代码的方式:https://gist.github.com/2585965。 –

相关问题