Подтвердить что ты не робот

Селекторы атрибутов jQuery: как выполнить запрос для атрибута с пользовательским пространством имен

Предположим, у меня есть простой документ XHTML, который использует собственное пространство имен для атрибутов:

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

Как я могу сопоставить каждый элемент с определенным пользовательским атрибутом с помощью jQuery? Использование

$("div[custom:attr]")

не работает. (Пробовал только Firefox, пока).

4b9b3361

Ответ 1

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

Ответ 3

синтаксис для сопоставления по атрибуту:

$( "DIV [customattr = бла]" ) совпадения --div customattr = "bla" -

$( "[customattr]" ) соответствует всем тегам с атрибутом "customattr"

с атрибутами пространства имен, такими как "custom: attr", который не работает

Здесь вы можете найти хороший обзор: http://www.pamaya.com/jquery-selectors-and-attribute-selectors-reference-and-examples/

Ответ 5

Вот реализация пользовательского селектора, который работает для меня.

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