的 Jquery 选择器中的元素
我们使用 jQuery 来解析一些 HTML。然后我需要遍历该文档并找到一些元素。在我需要查找的元素中,有 元素。
这对于提取所有 元素非常有效:
$(string).find("a")
但这对于提取 元素不起作用:
$(string).find("link")
string 参数是 html 内容(例如在请求中收到的)。
知道为什么吗? (我猜 find
仅适用于 元素)。另外,关于如何实际提取这些
元素有什么想法吗?
We use jQuery to parse some HTML. I then need to traverse that document and find some elements. Among the elements I need to find, there are the <link>
elements.
This works perfectly well to extract all the <a>
elements:
$(string).find("a")
but this doesn't work to extract the <link>
elements :
$(string).find("link")
The string
parameter is the html content (e.g. received on a request).
Any idea why? (I guess that the find
only applies to the <body>
elements). Also, any idea on how to actually extract these <link>
elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自您用于
$(string)文档 code> (这是函数
jQuery( html, [ownerDocument] )
):尽量不要使用 jQuery 操作整个 HTML 文档。
请特别注意,独立 HTML 片段中的
link
节点 可以“找到”很好。From the documentation of the feature you're using for
$(string)
(which is the functionjQuery( html, [ownerDocument] )
):Try not to use jQuery to manipulate entire HTML documents.
Note, in particular, that a
link
node in a standalone snippet of HTML can be "found" just fine.嗯,根据我在 中找到的内容jQuery 的源代码,引擎本身不会创建未“正确定位”的标签(或片段)。即使传递一个字符串,jQuery 也会识别出已经提供了 header,并且不会生成它。毕竟,当 jQuery 传递一个 HTML 字符串时,它实际上是在调用document.createElement< /code> 并创建这些元素的数组列表。
编辑:经过更多调查后,看起来实际上是浏览器限制了元素创建,而不是 jQuery。不管怎样,你都会留下缺失的标签。这让我得出下面同样的结论。
尽管我不喜欢它,但可能是时候进行正则表达式/字符串操作了。
Well, based on what I can find in the source code of jQuery, the engine itself will not create tags (or fragments) that are not "properly seated". Even when passing a string, jQuery recognizes that the header has already been supplied and will not generate it.After all, when jQuery is passed a string of HTML, it's actually callingdocument.createElement
and creating an array list of those elements.EDIT: After a little more investigation, it looks like it's the browser actually limiting element creation, not jQuery. Either way, you're left with absent tags. Which brings me to my same conclusion below.
As much as I don't like it, may be time for regex/string manipulation.
jQuery 无法做到这一点,但您的浏览器可以:(不要像某些人建议的那样尝试使用正则表达式解析 HTML。)
请注意,XML 区分大小写,因此您需要使用与其相同的大小写来搜索“LINK”在 HTML 中。
jQuery can't do it, but your browser can: (Do not try to parse HTML with a regex as someome suggested.)
Be aware that XML is case sensitive, so you need to search for 'LINK' using the same case as it is in the HTML.
就像@pimvdb指出的那样,这不起作用:
解释是正确的:
但这种方式有效:
对于一些说第二种方法不起作用的人: http://jsfiddle.net/埃里克彼得鲁/5Qs3M/。但当然它显然找不到不在 DOM 上的元素(即在
head
上)。Like @pimvdb pointed, this don't work:
The explanation is right:
But this way work:
And for some guys that said the second isn't working: http://jsfiddle.net/ErickPetru/5Qs3M/. But of course it obviously don't find elements that aren't on the DOM (i.e. on the
head
).