从HTML代码段创建节点列表后,.find()未按预期工作

.find() not working as expected after creating node list from HTML snippet

本文关键字:工作 find 节点 代码 HTML 段创建 创建 列表      更新时间:2023-09-26

我有以下使用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

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

您需要使用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
<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>