从HTML片段创建节点列表后,.find()无法按预期工作

Dan*_*ens 2 javascript jquery jquery-selectors

我使用jQuery有以下Javascript代码:

var html = '<a href="http://foo.example.com">Foo/a> | ' + 
           '<a href="http://bar.example.com">Bar</a>';
var aTags = $(html).find('a');
console.log(aTags.length); // => 0
Run Code Online (Sandbox Code Playgroud)

为什么是aTags空数组而不是2个<a>节点的数组?

Aru*_*hny 5

你需要使用,filter()因为find()试图找到jQuery对象引用的元素的后代元素,在你的字符串中,a元素位于根,所以find()将无法找到它们

var html = '<a href="http://foo.example.com">Foo/a> | ' +
  '<a href="http://bar.example.com">Bar</a>';
var aTags = $(html).filter('a');
snippet.log(aTags.length); // => 0
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)