2

Using jQuery, I am trying to find all elements with a data-inject attribute from an HTML string returned from the server. Here's an example HTML string:

var html = '<div class="container-fluid">
              <div class="row-fluid">
                <div data-inject="ViewModel1" class="span12"></div>
              </div>
            </div>
            <div data-inject="ViewModel2" class="navbar navbar-fixed-bottom"></div>';

I can't seem to find a way to get both divs and the problem seems to be the fact that I'm starting with a HTML string.

Here's a fiddle showing that just querying the DOM with $('[data-inject]') returns the two elements as expected. However, querying the HTML string with $('[data-inject]', html) only returns one element (the ViewModel1 element).

Anyone know what I'm doing wrong and how to get the expected result?

4

1 回答 1

6

那是因为你没有根元素。只是在查询期间临时使用 wrapAll 。

var html = '<div class="container-fluid"><div class="row-fluid"><div data-inject="TowerLogsViewModel" class="span12"></div></div></div><div data-inject="TowerLogFormViewModel" class="navbar navbar-fixed-bottom"></div>';
var $html = $(html);

$('[data-inject]', $html.wrapAll($('<div>')).parent()).each(function (ix, el) {
    console.log($(el).data('inject'));
});

演示

由于没有根元素,该集合将从集合data-inject中的第一个元素中找到,即<div class="container-fluid">您只能得到一个。如果你使用过滤器,你只会得到另一个。因此暂时包装它们。

于 2013-07-08T21:45:14.097 回答