似乎使用:contains(sub)
选择的元素与 sub
包含<
或>
无法联系到他们的 parent 。
以下示例应该说明我在 Safari 和 Camino(Mac 上的 Gecko)中遇到的问题:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<p><strong>bar</strong></p>
<p><strong><foo></strong></p>
<script type="text/javascript">
alert($('body strong:contains("bar")').length);
alert($('body strong:contains("bar")').parent().length);
alert($('body strong:contains("<foo>")').length);
alert($('body strong:contains("<foo>")').parent().length); // this fails
alert($('body strong').length);
alert($('body strong').parent().length); // two p elements
alert($('body strong').parent().parent().length); // one body
</script>
</body>
</html>
输出是:
1
1
1
0
2
2
1
有什么想法为什么第四个是 0
而不是1
,或者我该如何规避这个问题?
This page提到在选择器中转义名称,但这也不起作用(而且,我不确定它是否适用)。
最佳答案
免责声明:这不是解决方案/解决方法使用 Tatu's answer为此,这只是对问题的描述,以及是什么导致好奇的人出现奇怪的行为。
问题的根源就在这里,the regex that jQuery uses to identify an HTML Fragment :
/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/
哪个确实与您的选择器匹配:
body strong:contains("<foo>")
alert(/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/.test('body strong:contains("<foo>")'));
所以它认为它是一个 HTML 片段..所以总的来说,这些目前是等效的:
$('body strong:contains("<foo>")');
$('<foo>');
看到第二个可以更清楚地说明它是一个文档片段......它没有父级。它占据匹配数组中的第二个位置,您可以看到它只是 <foo>
, again try it out :
alert(/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/.exec('body strong:contains("<foo>")')[1]);
这会导致您最终得到 this code path in jQuery's $()
,构建一个片段。
所以简而言之是的,我认为这是一个 jQuery 错误。
关于jQuery 元素无法选择parent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3812280/