我希望能够从
HTML字符串构建一个jQuery对象并直接在里面搜索.
例:
htmlString = '
Foo
$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插入,代码看起来更清晰.