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插入和代码看起来更清晰的给我。
谢谢马特,这很清楚。我没有想到这个关于后代和兄弟姐妹的微妙之处,我感到很愚蠢。以下是我重构代码的方式:https://gist.github.com/2585965。 –