jquery - 为什么 .filter 可以找到标签而 .find 却不能?

标签 jquery

在 Chrome 控制台中尝试这两行(当然还有 jQuery 上下文):

$('<head><title>FooBar</title></head>').find('title')

将产生[] ,但是

$('<head><title>FooBar</title></head>').filter('title')

给出[<title>​FooBar​</title>​] 。但在这个例子中,<title> <head> 的后代,所以不应该使用 find 找到它?

有人能解释一下为什么不吗?

最佳答案

因为$('<head><title>FooBar</title></head>')没有做你认为它正在做的事情。

The jQuery docs explain当您要求 jQuery 以这种方式创建一些 HTML 对象时会发生什么:

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) — $( "<img />" ) or $( "<img>" ), $( "<a></a>" ) or $( "<a>" ) — jQuery creates the element using the native JavaScript createElement() function.

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.

已添加强调。

尝试运行 $('<head><title>FooBar</title></head>')在你的 JavaScript 控制台中,你会看到它只返回 <title>元素。 <head>已被您的浏览器删除。我在 Firebug 中的结果是:

Screenshot of the results in Firebug

Filter() 在元素集中搜索与选择器匹配的元素。您有一组由 <title> 组成的集合。元素,因此它返回该元素。与此同时,Find() 会查看您的 <title> 内部。 child 元素 <title>元素并发现根本没有返回!

关于jquery - 为什么 .filter 可以找到标签而 .find 却不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17396088/

相关文章:

javascript - 异步完成后如何执行另一个功能?

javascript - 通过 JQuery .change 重新加载 javascript 函数会添加之前运行中的变量

javascript - 如何固定绝对溢出元素相对于相对父元素的位置?

javascript - PHP 无法添加更多行(表单重复器)

javascript - .stop(true) 似乎并没有真正清除队列?

javascript - 将单选按钮添加到自动完成字段

javascript - 使用相同的输入文件标签获取元素名称

jquery - 使用 jquery 在列表项中添加 div

javascript - 表格行未拉伸(stretch)至 100% 宽度

javascript - 在jquery中添加哈希