我有以下 jQuery 行:
$('<html><a href="cnn.com">hi</a></html>').find('a')
我希望结果是一组包含一个元素的包装。然而,结果是一个空数组 ([]
)。为什么?
-- 编辑--
出于某种原因,下面的代码有效。
$('<html><div><a href="cnn.com">hi</a></div></html>').find('a');
为什么会这样?
最佳答案
那是因为 html
解析字符串时删除元素:
> $('<html><a href="cnn.com">hi</a></html>')
[<a href="cnn.com">hi</a>]
即当前集合包含一个您尝试添加的元素 find()
.作为顶级a
元素没有(不能)有a
子孙find()
调用将返回一个空集合。
来自 jQuery documentation :
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's
.innerHTML
property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as<html>
,<title>
, or<head>
elements. As a result, the elements inserted may not be representative of the original string passed.
编辑:第二个片段可以find()
a
html
时的元素元素被剥离集合的顶级元素是div
确实有 a
的元素后裔。
关于javascript - JQuery 为函数 'find' : 奇怪地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29341687/