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 の挿入が 1 つだけになり、コードがより明確に見えます。