我希望能够从HTML字符串构建一个jQuery对象并直接在里面搜索.
例:
htmlString = '<h3>Foo</h3><div class="groups"></div>'
$html = $(htmlString)
$groups = $html.find('.groups') // Returns []. WTF?
Run Code Online (Sandbox Code Playgroud)
我希望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)
@
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种更优雅的方式来实现相同的结果.
谢谢!
谢谢马特,很清楚.我没有想到关于后代和兄弟姐妹的这种微妙之处,我觉得很愚蠢.
所以我重构了我的代码:
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)
@
Run Code Online (Sandbox Code Playgroud)
现在只有一个DOM插入,代码看起来更清晰.
这是因为find()搜索jQuery对象中元素的后代,但.groups元素是 jQuery对象中的元素,因此不会匹配.
相反,您需要使用filter()搜索当前元素.
htmlString = '<h3>Foo</h3><div class="groups"></div>'
$html = $(htmlString)
$groups = $html.filter('.groups');
Run Code Online (Sandbox Code Playgroud)
但是,如果你再有htmlString的<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'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4016 次 |
| 最近记录: |