34

属性にカスタム名前空間を使用する単純な XHTML ドキュメントがあるとします。

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

jQuery を使用して特定のカスタム属性を持つ各要素を一致させるにはどうすればよいですか? 使用する

$("div[custom:attr]")

動作しません。(これまでのところ、Firefox のみで試しました。)

4

5 に答える 5

43

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.');
});
于 2008-09-18T11:42:08.583 に答える
19

これは、いくつかの条件で機能します。

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

ただし、より高度な方法については、このXML名前空間jQueryプラグインを参照してください。

于 2010-02-02T13:55:44.110 に答える
6

属性によるマッチングの構文は次のとおりです。

$("div[customattr=bla]")マッチdiv customattr="bla"

$("[customattr]")属性を持つすべてのタグに一致します"customattr"

'custom:attr'機能しないなどの名前空間属性を持つ

ここでは、良い概要を見つけることができます。

于 2010-05-28T09:17:25.827 に答える
3

を使用する必要があります$('div').attr('custom:attr')

于 2008-09-18T10:56:41.110 に答える
2

これは、私のために機能するカスタムセレクターの実装です。

// Custom jQuery selector to select on custom namespaced attributes
$.expr[':'].nsAttr = function(obj, index, meta, stack) {

    // if the parameter isn't a string, the selector is invalid, 
    // so always return false.
    if ( typeof meta[3] != 'string' )
        return false;

    // if the parameter doesn't have an '=' character in it, 
    // assume it is an attribute name with no value, 
    // and match all elements that have only that attribute name.
    if ( meta[3].indexOf('=') == -1 )
    {
        var val = $(obj).attr(meta[3]);
        return (typeof val !== 'undefined' && val !== false);
    }
    // if the parameter does contain an '=' character, 
    // we should only match elements that have an attribute 
    // with a matching name and value.
    else
    {
        // split the parameter into name/value pairs
        var arr = meta[3].split('=', 2);
        var attrName  = arr[0];
        var attrValue = arr[1];

        // if the current object has an attribute matching the specified 
        // name & value, include it in our selection.
        return ( $(obj).attr(attrName) == attrValue );
    }
};

使用例:

// Show all divs where the custom attribute matches both name and value.
$('div:nsAttr(MyNameSpace:customAttr=someValue)').show();

// Show all divs that have the custom attribute, regardless of its value.
$('div:nsAttr(MyNameSpace:customAttr)').show();
于 2012-04-04T16:21:35.487 に答える