jQuery属性选择器:如何使用自定义名称空间查询属性

时间:2020-03-06 14:20:44  来源:igfitidea点击:

假设我有一个简单的XHTML文档,该文档对属性使用了自定义名称空间:

<html xmlns="..." xmlns:custom="http://www.example.com/ns">
    ...
    <div class="foo" custom:attr="bla"/>
    ...
</html>

如何使用jQuery匹配具有特定自定义属性的每个元素?使用

$("div[custom:attr]")

不起作用。 (到目前为止,仅尝试使用Firefox。)

解决方案

我们应该使用$('div')。attr('custom:attr')`。

jQuery不直接支持自定义名称空间,但是我们可以使用过滤器功能找到所需的div。

// find all divs that have custom:attr
$('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() {
  // matched a div with custom::attr
  $(this).html('I was found.');
});

这在某些情况下有效:

$(" div [custom \:attr]")`

但是,有关更高级的方法,请参见此XML命名空间jQuery插件。

按属性匹配的语法为:

$(" div [customattr = bla]")div customattr =" bla"`相匹配

$(" [customattr]")将所有标签与属性"" customattr"匹配。

具有名称空间属性,如"'custom:attr'`",则无法正常工作

在这里我们可以找到很好的概述。