【发布时间】:2010-10-11 22:15:51
【问题描述】:
我一直在尝试几种不同的方法来过滤在我的 html 中找到的特定节点。
这里是一些示例 html:
<body>
<div ui:component="component1"></div>
<ul ui:component="component2"></ul>
<article ui:component="component3"></article>
</body>
我已经通过一个简单的过滤器成功地匹配了项目:
// returns div, ul, article
$('[ui\\:component]').each();
但是,当我开始根据父节点过滤它时,它开始对我失败。我试过了:
$('[ui\\:component]', $('body')); // returns []
$('body').find('[ui\\:component]'); // returns []
$('body').filter('[ui\\:component]'); // returns []
$('body').find('*').filter('[ui\\:component]'); // returns []
我在这里做错了什么?起初我以为它可能是 ui 命名空间,但将其添加到 html doc 或 body 似乎没有任何意义。非常感谢帮助
全文如下:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div ui:component="component1"></div>
<ul ui:component="component2"></ul>
<article ui:component="component3"></article>
</body>
<script type="text/javascript">
$(document).ready(function() {
// returns div, ul, article
console.log($('[ui\\:component]'));
// these all return nada
console.log($('[ui\\:component]', $('body')));
console.log($('body').find('[ui\\:component]'));
console.log($('body').filter('[ui\\:component]'));
console.log($('body').find('*').filter('[ui\\:component]'));
});
</script>
</html>
【问题讨论】:
-
注意:删除命名空间 ui: 似乎可以正常工作。但我不喜欢名字冲突.......
-
在使用 Firefox 3.5 时,我可以使用
$("body *[ui\\:component]")让它工作,但是我没有测试任何其他浏览器,所以即使它是 jQuery,我也不知道这是否会到处工作。虽然我知道不希望命名空间冲突,但浏览器和 js 往往对命名空间没有很好的支持。 -
@Thomas - 这类似于在问题中正常工作的代码
$('[ui\\:component]')。选择器之所以有效,是因为它在可用时使用本机querySelectorAll()(包括 Firefox 3.5)。但是.find()和.filter()不起作用。 -
谢谢。现在我已经删除了命名空间——这导致了不正确的 find();
-
@patrick - 有道理。所以很可能,除非是 IE8+、FF3.5+(至少根据 quirksmode.org),否则这些选择器将不起作用。