javascript - JQuery 为函数 'find' : 奇怪地工作

标签 javascript jquery

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

相关文章:

javascript - Jquery 计时器只运行一次?

javascript - 在 jQuery 中打开一个元素时如何关闭其他打开的元素?

javascript - 我可以从服务器向客户端 GRPC 发送自定义错误消息吗?

javascript - 主干 - View 未渲染

javascript - 如何按子对象对对象数组进行分组?

javascript - javascript中如何在一段时间后触发按钮的点击事件

javascript - 交换机内的回调

javascript - 如何在D3中渲染对象数据?

jquery - CSS 变换(三 Angular 形)

javascript - 如何使用引导日期选择器自动格式化日期