jQuery attribute selectors: How to query for an attribute with a custom namespace

前端 未结 5 1523
一整个雨季
一整个雨季 2020-12-24 11:46

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


            


        
相关标签:
5条回答
  • 2020-12-24 12:15

    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.');
    });
    
    0 讨论(0)
  • 2020-12-24 12:18

    This works in some conditions:

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

    However, for a more advanced method, see this XML Namespace jQuery plug-in

    0 讨论(0)
  • 2020-12-24 12:18

    You should use $('div').attr('custom:attr').

    0 讨论(0)
  • 2020-12-24 12:19

    Here is an implementation of a custom selector that works for me.

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

    Example usage:

    // 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();
    
    0 讨论(0)
  • 2020-12-24 12:20

    the syntax for matching by attribute is:

    $("div[customattr=bla]") matches div customattr="bla"

    $("[customattr]") matches all tags with the attribute "customattr"

    with namespace attributes like 'custom:attr' its not working

    Here you can find a good overview.

    0 讨论(0)
提交回复
热议问题