使用jQuery的"find"查找jQuery文档片段中的元素

Gar*_*ary 5 html javascript jquery fragment jquery-selectors

如果我这样做,然后02返回,分别为:

$html = $(document.createDocumentFragment());
$html.append('<a href="#">First link</a><a href="#">Second link</a>');

console.log($html.find('a').length);
console.log($html[0].querySelectorAll('a').length);
Run Code Online (Sandbox Code Playgroud)

我怎样才能使jQuery方法也能工作?基本上,我希望能够使用jQuery搜索文档片段,而不需要使用本机JavaScript DOM函数来回切换.

0x8*_*890 0

您需要将字符串片段传递到 jQuery 并保存对其的引用:

var $html = $(document.createDocumentFragment());
var $fragment = $('<a href="#">First link</a><a href="#">Second link</a>');
$html.append($fragment);

console.log($fragment.filter('a').length);
console.log($html[0].querySelectorAll('a').length);
Run Code Online (Sandbox Code Playgroud)

然后就可以遍历解析后的片段了。请注意,此处find已替换为filter,因为我们有对元素集合的引用a,并且find仅适用于包含元素的子元素。

这将按预期2记录。2演示: http: //jsfiddle.net/fec9csxu/