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

问题描述:

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

Suppose I have a simple XHTML document that uses a custom namespace for attributes:

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

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

How do I match each element that has a certain custom attribute using jQuery? Using

$("div[custom:attr]")

不起作用。 (到目前为止只用Firefox试过。)

does not work. (Tried with Firefox only, so far.)

jQuery 不直接支持自定义命名空间,但您可以使用过滤功能找到您要查找的div。

jQuery does not support custom namespaces directly, but you can find the divs you are looking for by using filter function.

// 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.');
});