5

我希望能够从一串 HTML 构建一个 jQuery 对象并直接在里面搜索。

例子:

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

我希望这find实际上找到了div元素。

如果您想了解更多关于我的问题的上下文,我开发了一个 Backbone 应用程序并渲染某些视图,我有这样的事情:

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 插入,代码看起来更清晰。

4

1 回答 1

8

这是因为find()在 jQuery 对象中搜索元素的后代,但该.groups元素jQuery 对象中的元素,因此不会匹配。

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

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

但是,如果您当时拥有htmlStringof <h3><span class="bar">Foo</span></h3><div class="groups"></div>,您将找不到.bar; 这将是一个find()电话。

因此,您需要同时检查两者;

htmlString = '<h3>Foo</h3><div class="groups"></div>'
$html      = $(htmlString)
$groups    = $html.find('.groups').add($html.filter('.groups'));   
于 2012-05-03T10:42:48.090 回答